saaslayer 0.3.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 (60) hide show
  1. package/README.md +105 -16
  2. package/bin/saaslayer.js +321 -60
  3. package/package.json +3 -2
  4. package/src/aws-sigv4.js +74 -26
  5. package/src/commands/access-admins.js +2 -2
  6. package/src/commands/admin-allowlist.js +23 -3
  7. package/src/commands/api-keys.js +83 -0
  8. package/src/commands/audit.js +77 -0
  9. package/src/commands/aws.js +355 -82
  10. package/src/commands/binding-handoff.js +174 -0
  11. package/src/commands/bindings.js +111 -0
  12. package/src/commands/catalog.js +30 -3
  13. package/src/commands/deploy.js +33 -10
  14. package/src/commands/env-export.js +58 -0
  15. package/src/commands/first-admin.js +15 -4
  16. package/src/commands/foundation.js +75 -117
  17. package/src/commands/hooks.js +271 -0
  18. package/src/commands/integration-credentials.js +1 -1
  19. package/src/commands/lifecycle.js +149 -24
  20. package/src/commands/login-domain.js +259 -0
  21. package/src/commands/permission-orgs.js +80 -0
  22. package/src/commands/release-manifest.js +17 -8
  23. package/src/commands/service-principals.js +42 -5
  24. package/src/commands/settings.js +21 -5
  25. package/src/commands/sms-registration.js +182 -0
  26. package/src/commands/sms.js +178 -0
  27. package/src/commands/social.js +265 -0
  28. package/src/commands/support-staff.js +72 -0
  29. package/src/commands/users-management.js +2 -20
  30. package/src/commands/users.js +56 -11
  31. package/src/commands/versions.js +61 -0
  32. package/src/connection-proof.js +41 -0
  33. package/src/deployments.js +1 -1
  34. package/src/foundation-change-set.js +180 -0
  35. package/src/foundation-home.js +121 -0
  36. package/src/foundation-template.js +51 -10
  37. package/src/foundation-trust-write.js +379 -0
  38. package/src/iam-session.js +14 -8
  39. package/src/login-domain.js +139 -0
  40. package/src/login-methods.js +118 -0
  41. package/src/module-catalog.js +3 -2
  42. package/src/release-manifest.js +11 -4
  43. package/src/scope.js +3 -1
  44. package/src/settings.js +85 -13
  45. package/src/sms/number.js +37 -0
  46. package/src/sms/registration-fields.js +167 -0
  47. package/src/sms/registration-validate.js +151 -0
  48. package/src/sms/registration.js +216 -0
  49. package/src/sms/release.js +55 -0
  50. package/src/sms/scope.js +86 -0
  51. package/src/sms/status.js +181 -0
  52. package/src/ssm-api.js +31 -0
  53. package/src/trust-entries.js +350 -0
  54. package/src/user-service-instance.js +27 -0
  55. package/src/users-api.js +55 -8
  56. package/src/users-import/checkpoint.js +76 -0
  57. package/src/users-import/import.js +233 -24
  58. package/src/versions.js +80 -0
  59. package/templates/saaslayer-foundation-region.yml +45 -1
  60. package/templates/saaslayer-foundation.yml +747 -296
@@ -0,0 +1,118 @@
1
+ // User-service sign-in method rules on the CLI side: the permanent primary and the add-only opposite secondary a create
2
+ // or settings change asks for, what it needs (SMS countries, the phone first admin), and the preview shown before it is sent.
3
+ 'use strict'
4
+
5
+ /**
6
+ * @typedef {'email'|'phone'} LoginMethod
7
+ * @typedef {Record<string, { value?: unknown, source?: string }>} CurrentValues setting name → current value and source
8
+ * @typedef {{ primary: LoginMethod, added: Array<{ loginMethod: LoginMethod, role: 'primary'|'secondary' }>, phone: boolean,
9
+ * problems: string[], preview: string[] }} SignInChange
10
+ */
11
+
12
+ const USER_SERVICE = 'user-service'
13
+ const PRIMARY = 'PrimaryLoginMethod'
14
+ const COUNTRIES = 'PhoneSmsAllowedCountries'
15
+ /** The add-only flag that adds the opposite method as a secondary pool, per primary. */
16
+ const SECONDARY_FLAG = { email: 'EnablePhoneLogin', phone: 'EnableEmailLogin' }
17
+ /** @type {Record<LoginMethod, LoginMethod>} */
18
+ const OPPOSITE = { email: 'phone', phone: 'email' }
19
+ // Mirrors the deployer's adminPhoneNumber rule (E.164).
20
+ const E164 = /^\+[1-9]\d{6,14}$/
21
+ const PRICING = 'https://aws.amazon.com/end-user-messaging/pricing/'
22
+ const ONE_WAY = 'This adds another login method. In v1 this accepted choice cannot be turned off, including if deployment needs a retry.'
23
+ const SMS_FEES = 'SMS messages incur usage charges; retained sending numbers or campaigns may also have recurring fees.'
24
+
25
+ /** @param {unknown} value */
26
+ const isTrue = (value) => value === true || value === 'true'
27
+
28
+ /**
29
+ * A phone number with all but its last four digits hidden, e.g. +*******0123; anything shorter is fully hidden.
30
+ * @param {string} phoneNumber
31
+ * @returns {string}
32
+ */
33
+ function maskPhoneNumber(phoneNumber) {
34
+ const digits = String(phoneNumber).replace(/^\+/, '')
35
+ if (digits.length <= 4) return '+****'
36
+ return `+${'*'.repeat(digits.length - 4)}${digits.slice(-4)}`
37
+ }
38
+
39
+ /**
40
+ * The sign-in change a user-service create or settings patch makes: its permanent primary, the pools it adds, what it
41
+ * still needs (problems, never echoing a phone number) and the preview lines (empty for an email-only request, so the
42
+ * existing email UX is unchanged).
43
+ * @param {{ op: 'create'|'update', values?: Record<string, unknown>, current?: CurrentValues, adminPhoneNumber?: string, env?: string }} input
44
+ * values: the request's user-service settings; current: the deployment's user-service settings (update only)
45
+ * @returns {SignInChange}
46
+ */
47
+ function signInChange({ op, values = {}, current = {}, adminPhoneNumber, env }) {
48
+ /** @param {string} name */
49
+ const currentValue = (name) => (current[name] ? current[name].value : undefined)
50
+ /** @type {LoginMethod} */
51
+ const primary = (op === 'create' ? values[PRIMARY] : currentValue(PRIMARY)) === 'phone' ? 'phone' : 'email'
52
+ const flag = SECONDARY_FLAG[primary]
53
+ const secondaryBefore = op === 'update' && isTrue(currentValue(flag))
54
+ const secondaryRequested = isTrue(values[flag])
55
+ /** @type {SignInChange['added']} */
56
+ const added = []
57
+ if (op === 'create' && primary === 'phone') added.push({ loginMethod: 'phone', role: 'primary' })
58
+ if (secondaryRequested && !secondaryBefore) added.push({ loginMethod: OPPOSITE[primary], role: 'secondary' })
59
+ const phone = primary === 'phone' || secondaryBefore || secondaryRequested
60
+ const addsPhone = added.some((a) => a.loginMethod === 'phone')
61
+
62
+ const problems = []
63
+ const countriesGiven = values[COUNTRIES] !== undefined && values[COUNTRIES] !== null && values[COUNTRIES] !== ''
64
+ const countriesSet = countriesGiven || (op === 'update' && current[COUNTRIES] && current[COUNTRIES].source === 'set')
65
+ if (addsPhone && !countriesSet) {
66
+ problems.push(`${USER_SERVICE}.${COUNTRIES} is required with phone sign-in: name the countries it may send SMS to, e.g. US or US,CA`)
67
+ }
68
+ if (op === 'create') {
69
+ const admin = typeof adminPhoneNumber === 'string' ? adminPhoneNumber.trim() : ''
70
+ if (admin && !E164.test(admin)) problems.push('the first admin phone number must be in E.164 form, like +15555550100')
71
+ else if (admin && primary !== 'phone') problems.push(`the first admin phone number applies only to a phone-primary deployment (${USER_SERVICE}.${PRIMARY}=phone); name the first admin by email`)
72
+ else if (!admin && primary === 'phone') problems.push('a phone-primary deployment names its first admin by phone number (E.164, like +15555550100); an email is a contact only')
73
+ }
74
+
75
+ const preview = []
76
+ if (added.length) {
77
+ if (op === 'create') preview.push(`Primary sign-in: ${primary} (permanent: set when the deployment is created, never changed)`)
78
+ if (op === 'create' && primary === 'phone') preview.push('Phone primary: there is no email account or email fallback; social and passwordless sign-in are not available')
79
+ for (const { loginMethod, role } of added) {
80
+ if (role !== 'secondary') continue
81
+ preview.push(`${ONE_WAY}${loginMethod === 'phone' ? ` ${SMS_FEES}` : ''}`)
82
+ preview.push(`Adds: a second Cognito user pool for ${loginMethod} sign-in with its own login client. It offers native password sign-in only (no social or passwordless), with its own passwords and MFA; an account in each pool stays separate until its owner links them`)
83
+ }
84
+ if (phone) {
85
+ const countries = countriesGiven ? String(values[COUNTRIES]) : currentValue(COUNTRIES) !== undefined ? String(currentValue(COUNTRIES)) : '—'
86
+ preview.push(`SMS countries: ${countries} (countries can be added later, never removed)`)
87
+ preview.push(`Before phone sign-in is accepted its SMS setup is checked (sending number, registration, production access, spend limit; \`saaslayer sms status${env ? ` --env ${env}` : ''}\` shows it); a failed check saves nothing`)
88
+ }
89
+ preview.push(addsPhone
90
+ ? `Costs: AWS End User Messaging bills each SMS sent and a sending number or registration (campaign) can bill monthly without traffic; Cognito bills each user pool's monthly active users separately. Why: phone sign-in sends its verification, recovery and MFA codes by SMS. Prices: ${PRICING}`
91
+ : 'Costs: Cognito bills the added user pool\'s monthly active users separately. Why: the added sign-in method is a second user pool')
92
+ if (op === 'create' && primary === 'phone' && typeof adminPhoneNumber === 'string' && E164.test(adminPhoneNumber.trim())) {
93
+ preview.push(`First admin: ${maskPhoneNumber(adminPhoneNumber.trim())} (gets the first sign-in by SMS; delivery is proven only when they activate)`)
94
+ }
95
+ }
96
+ return { primary, added, phone, problems, preview }
97
+ }
98
+
99
+ /**
100
+ * The next action for a sign-in refusal the control plane answered with, or null for any other refusal.
101
+ * @param {{ body?: { errors?: Array<{ code?: string }>, code?: string } }} err
102
+ * @param {string} [env]
103
+ * @returns {string|null}
104
+ */
105
+ function signInRefusalHint(err, env) {
106
+ const body = (err && err.body) || {}
107
+ const code = (body.errors && body.errors[0] && body.errors[0].code) || body.code
108
+ const scope = env ? ` --env ${env}` : ''
109
+ if (code === 'SMS_SETUP_REQUIRED') return `nothing was saved: finish the SMS setup each code names (\`saaslayer sms status${scope}\` shows it; \`saaslayer sms setup${scope}\` installs a sending number, \`saaslayer sms register${scope}\` registers it), then run this again`
110
+ if (code === 'LOGIN_METHOD_ADD_ONLY') return `an accepted sign-in method is never turned off; to resume a failed one run \`saaslayer update --retry${scope}\``
111
+ if (code === 'PRIMARY_LOGIN_IMPLICIT') return 'the primary sign-in method is always on; only the opposite method can be added (EnablePhoneLogin on an email primary, EnableEmailLogin on a phone primary)'
112
+ if (code === 'CONTRACT_INCOMPATIBLE') return `that release cannot carry the sign-in methods this deployment accepted, so it is never deployed here: stay on the deployed release (\`saaslayer update --retry${scope}\`) or move to a newer one`
113
+ if (code === 'ADMIN_PHONE_REQUIRED') return 'a phone-primary deployment names its first admin by phone number: pass --admin-phone-number (deploy) or --phone-number (first-admin recover)'
114
+ if (code === 'ADMIN_PHONE_INAPPLICABLE') return 'this deployment\'s primary sign-in is email: name the first admin by email'
115
+ return null
116
+ }
117
+
118
+ module.exports = { USER_SERVICE, SECONDARY_FLAG, maskPhoneNumber, signInChange, signInRefusalHint }
@@ -40,14 +40,15 @@ function checkModuleIds(ids, modules) {
40
40
  }
41
41
 
42
42
  /**
43
- * Every selected module's dependencies must be selected too.
43
+ * Every selected module's deploy-phase dependencies must be selected too. A seed-phase source is optional: the seed
44
+ * uses it when it is in the deployment and skips it otherwise (e.g. permissions-service without user-service).
44
45
  * @param {string[]} ids
45
46
  * @param {CatalogModule[]} modules
46
47
  */
47
48
  function checkDependencies(ids, modules) {
48
49
  for (const id of ids) {
49
50
  const m = modules.find((x) => x.id === id)
50
- for (const dep of (m && m.attributes.dependencies) || []) {
51
+ for (const dep of ((m && m.attributes.dependencies) || []).filter((d) => d.phase !== 'seed')) {
51
52
  if (!ids.includes(dep.module)) throw new Error(`${id} needs ${dep.module} in the same deployment (${dep.phase}) — add it to --services`)
52
53
  }
53
54
  }
@@ -5,6 +5,7 @@ const crypto = require('crypto')
5
5
  const fs = require('fs')
6
6
  const path = require('path')
7
7
  const { PROTECTED_ENVS, readSettingsFile, checkPatch, valueProblem } = require('./settings')
8
+ const { SEMVER } = require('./versions')
8
9
 
9
10
  const MANIFEST_SCHEMA_VERSION = 1
10
11
  // The module whose service writes the permission docs direct-mode readers parse, and the setting that picks the format.
@@ -29,7 +30,7 @@ function directModeContract() {
29
30
  * @typedef {{ decisionEngineContract: number, writes: { permissionDoc: number, registrySnapshot: number } }} WriterRelease
30
31
  * @typedef {{ settings: string, settingsSha256?: string }} EnvironmentRef
31
32
  * @typedef {{ schemaVersion: 1, name?: string,
32
- * bundle: { revision: string, modules: Record<string, { settingsContractSha256: string }> },
33
+ * bundle: { revision: string, version?: string, modules: Record<string, { settingsContractSha256: string }> },
33
34
  * tooling: { cli: string, sdks?: Record<string, string> },
34
35
  * compatibility?: { permissions?: WriterRelease },
35
36
  * permissionsDirectMode?: { readers: unknown },
@@ -65,10 +66,12 @@ function validateManifest(doc) {
65
66
  if (doc.name !== undefined && (typeof doc.name !== 'string' || !doc.name)) problems.push('name must be a non-empty string')
66
67
 
67
68
  const bundle = doc.bundle
68
- if (!isObject(bundle)) problems.push('bundle is required: { revision, modules }')
69
+ if (!isObject(bundle)) problems.push('bundle is required: { revision, version?, modules }')
69
70
  else {
70
- onlyFields(bundle, ['revision', 'modules'], 'bundle.', problems)
71
+ onlyFields(bundle, ['revision', 'version', 'modules'], 'bundle.', problems)
71
72
  if (typeof bundle.revision !== 'string' || !COMMIT_SHA.test(bundle.revision)) problems.push('bundle.revision must be a full 40-character commit sha')
73
+ // The version the release moves by; revision stays the commit its contracts are checked at.
74
+ if (bundle.version !== undefined && (typeof bundle.version !== 'string' || !SEMVER.test(bundle.version))) problems.push('bundle.version must be MAJOR.MINOR.PATCH (e.g. 1.4.0)')
72
75
  if (!isObject(bundle.modules) || !Object.keys(bundle.modules).length) problems.push('bundle.modules must name at least one module')
73
76
  else {
74
77
  for (const [id, entry] of Object.entries(bundle.modules)) {
@@ -273,6 +276,7 @@ function preflightManifest({ manifest, env, current, targetSchemas, envPatch, re
273
276
  /** @type {import('./settings').SettingsPatch|null} */
274
277
  let patch = null
275
278
  let billing = []
279
+ let security = []
276
280
  if (envPatch) {
277
281
  /** @type {import('./settings').SettingsPatch} */
278
282
  const reduced = {}
@@ -285,7 +289,9 @@ function preflightManifest({ manifest, env, current, targetSchemas, envPatch, re
285
289
  }
286
290
  }
287
291
  try {
288
- billing = checkPatch(reduced, schemas, { op: 'update' }).billing
292
+ const checked = checkPatch(reduced, schemas, { op: 'update' })
293
+ billing = checked.billing
294
+ security = checked.security
289
295
  patch = reduced
290
296
  } catch (err) {
291
297
  add('settings', 'settings_invalid', err.message)
@@ -312,6 +318,7 @@ function preflightManifest({ manifest, env, current, targetSchemas, envPatch, re
312
318
 
313
319
  if (!reason && PROTECTED_ENVS.has(env)) add('reason', 'reason_required', `${env} is a protected environment: pass --reason <text>`)
314
320
  else if (!reason && billing.length) add('reason', 'reason_required', `${billing.join(', ')} changes billing: pass --reason <text>`)
321
+ else if (!reason && security.length) add('reason', 'reason_required', `${security.join(', ')} changes security: pass --reason <text>`)
315
322
 
316
323
  const fromRevisions = [...new Set(current.modules.map((m) => m.revision || '—'))]
317
324
  const moveRelease = current.modules.some((m) => m.revision !== target)
package/src/scope.js CHANGED
@@ -107,7 +107,9 @@ function formatDeployedProjects(projects, emptyProjectId) {
107
107
  * @returns {Promise<string[]>}
108
108
  */
109
109
  async function deployedProjectsHint(scope, flags) {
110
- const doc = await apiCall('GET', '/api/deployments', undefined, flags)
110
+ if (!scope.org.value) return ['select an organization with `saaslayer org use <id>` to list deployed projects']
111
+ const query = new URLSearchParams({ orgId: scope.org.value })
112
+ const doc = await apiCall('GET', `/api/deployments?${query}`, undefined, flags)
111
113
  return formatDeployedProjects(deployedProjects(doc.data || []), scope.project.value)
112
114
  }
113
115
 
package/src/settings.js CHANGED
@@ -4,13 +4,19 @@
4
4
  const fs = require('fs')
5
5
 
6
6
  /**
7
- * @typedef {{ name: string, type: string, description: string, group: string, updateBehavior: 'update-safe'|'create-only',
8
- * billingImpact: boolean, kind: 'deployment'|'runtime', secret: boolean, default?: unknown, allowed?: string[],
9
- * pattern?: string, patternDescription?: string, min?: number, max?: number, env?: string }} Setting
10
- * @typedef {{ module: string, revision: string, settings: Setting[], bindings?: Array<{ name: string, from: string }> }} SettingsSchema
7
+ * @typedef {{ name: string, type: string, description: string, group: string, updateBehavior: 'update-safe'|'create-only'|'add-only',
8
+ * billingImpact: boolean, securityImpact?: boolean, kind: 'deployment'|'runtime', secret: boolean, default?: unknown, allowed?: string[],
9
+ * pattern?: string, patternDescription?: string, min?: number, max?: number, env?: string,
10
+ * applicableWhen?: { setting: string, in: string[] }, authority?: 'commercial' }} Setting
11
+ * @typedef {{ schemaVersion?: number, module: string, revision: string, settings: Setting[], bindings?: Array<{ name: string, from: string }> }} SettingsSchema
11
12
  * @typedef {Record<string, Record<string, unknown>>} SettingsPatch module → setting name → value
12
13
  */
13
14
 
15
+ // Settings contract versions this CLI reads: 2 adds add-only settings and applicableWhen conditions; 3 adds securityImpact;
16
+ // 4 adds authority 'commercial' (a setting the customer's plan sets).
17
+ const SETTINGS_SCHEMA_VERSIONS = [1, 2, 3, 4]
18
+ // How a commercial setting (authority 'commercial') reads: its value comes from the customer's plan.
19
+ const PLAN_MANAGED = 'managed by your plan'
14
20
  // Mirrors the control-plane API's SSM parameter-name rule for secret references.
15
21
  const SSM_PARAMETER_NAME = /^\/[A-Za-z0-9_.\-/]{1,2047}$/
16
22
  const SSM_PREFIX = 'ssm:'
@@ -76,6 +82,19 @@ function mergePatches(...patches) {
76
82
  return out
77
83
  }
78
84
 
85
+ /**
86
+ * A settings schema from GET /api/modules/{module}/settings-schema, refused when its schemaVersion is one this CLI
87
+ * does not read (a newer contract format needs a newer CLI).
88
+ * @param {SettingsSchema} schema
89
+ * @returns {SettingsSchema}
90
+ */
91
+ function readableSchema(schema) {
92
+ if (!SETTINGS_SCHEMA_VERSIONS.includes(/** @type {number} */ (schema.schemaVersion))) {
93
+ throw new Error(`${schema.module} settings schema at ${schema.revision} is schemaVersion ${schema.schemaVersion}; this CLI reads ${SETTINGS_SCHEMA_VERSIONS.join(', ')}: upgrade the saaslayer CLI`)
94
+ }
95
+ return schema
96
+ }
97
+
79
98
  /**
80
99
  * What a value must be, or null when it fits the setting's type, allowed values, bounds and pattern.
81
100
  * @param {Setting} setting
@@ -117,17 +136,22 @@ function secretReference(value) {
117
136
  /**
118
137
  * Check a patch against each module's schema before anything is sent. Messages name the setting, never its value.
119
138
  * On update a secret is sent as `{ ssmParameter }` and null resets a setting; on create a secret is sent as its
120
- * parameter name and null is refused. Create-only and runtime settings are refused on update.
139
+ * parameter name and null is refused. Create-only and runtime settings are refused on update. A setting whose
140
+ * applicableWhen condition does not hold is refused in any value (on create the request's or default value decides; on
141
+ * update the deployment's current one), and on update an add-only setting accepts only true.
121
142
  * @param {SettingsPatch} patch
122
143
  * @param {Record<string, SettingsSchema>} schemas by module
123
- * @param {{ op: 'create'|'update' }} opts
124
- * @returns {{ patch: SettingsPatch, createOnly: string[], billing: string[] }}
144
+ * @param {{ op: 'create'|'update', current?: Record<string, Record<string, { value?: unknown }>> }} opts
145
+ * current: each module's current settings by name (update), as `settings get` reads them
146
+ * @returns {{ patch: SettingsPatch, createOnly: string[], billing: string[], security: string[] }} billing / security: the settings whose
147
+ * change needs a written reason
125
148
  */
126
- function checkPatch(patch, schemas, { op }) {
149
+ function checkPatch(patch, schemas, { op, current = {} }) {
127
150
  /** @type {SettingsPatch} */
128
151
  const out = {}
129
152
  const createOnly = []
130
153
  const billing = []
154
+ const security = []
131
155
  for (const [module, values] of Object.entries(patch)) {
132
156
  const schema = schemas[module]
133
157
  if (!schema) throw new Error(`${module} is not ${op === 'update' ? 'deployed in this deployment' : 'a module with a settings schema'}`)
@@ -147,8 +171,19 @@ function checkPatch(patch, schemas, { op }) {
147
171
  if (op === 'update' && setting.kind === 'runtime') {
148
172
  throw new Error(`${label} is a runtime setting; runtime settings cannot be written through the control plane yet (nothing was sent)`)
149
173
  }
174
+ if (setting.applicableWhen) {
175
+ const when = setting.applicableWhen
176
+ const condition = byName.get(when.setting)
177
+ const given = op === 'create' ? values[when.setting] : ((current[module] || {})[when.setting] || {}).value
178
+ const holds = String(given ?? (condition && condition.default !== undefined ? condition.default : ''))
179
+ if (!when.in.includes(holds)) throw new Error(`${label} applies only when ${when.setting} is ${when.in.join('|')} (it is ${holds}); leave it out`)
180
+ }
181
+ if (op === 'update' && setting.updateBehavior === 'add-only' && value !== true && value !== 'true') {
182
+ throw new Error(`${label} is add-only: it can be turned on, never off (a failed sign-in method is resumed with saaslayer update --retry)`)
183
+ }
150
184
  if (setting.updateBehavior === 'create-only') createOnly.push(label)
151
185
  if (setting.billingImpact) billing.push(label)
186
+ if (setting.securityImpact) security.push(label)
152
187
  if (value === null) {
153
188
  if (op === 'create') throw new Error(`${label}: null resets a setting on a standing deployment; leave it out on create`)
154
189
  out[module][name] = null
@@ -165,7 +200,7 @@ function checkPatch(patch, schemas, { op }) {
165
200
  out[module][name] = value
166
201
  }
167
202
  }
168
- return { patch: out, createOnly, billing }
203
+ return { patch: out, createOnly, billing, security }
169
204
  }
170
205
 
171
206
  /**
@@ -186,10 +221,11 @@ function displayValue(s) {
186
221
  function formatSchema(schema) {
187
222
  const lines = [`${schema.module} @ ${schema.revision}: ${schema.settings.length} setting(s)`]
188
223
  for (const s of schema.settings) {
189
- const flags = [s.type, s.updateBehavior, s.kind, s.secret ? 'secret' : null, s.billingImpact ? 'billing' : null].filter(Boolean).join(', ')
224
+ const flags = [s.type, s.updateBehavior, s.kind, s.secret ? 'secret' : null, s.billingImpact ? 'billing' : null, s.securityImpact ? 'security' : null, s.authority === 'commercial' ? PLAN_MANAGED : null].filter(Boolean).join(', ')
190
225
  const dflt = s.secret || s.default === undefined ? '' : ` default: ${JSON.stringify(s.default)}`
191
226
  const allowed = s.allowed ? ` allowed: ${s.allowed.join('|')}` : ''
192
- lines.push(` ${s.name} [${flags}] (${s.group})${dflt}${allowed}`)
227
+ const applies = s.applicableWhen ? ` applies when ${s.applicableWhen.setting} is ${s.applicableWhen.in.join('|')}` : ''
228
+ lines.push(` ${s.name} [${flags}] (${s.group})${dflt}${allowed}${applies}`)
193
229
  lines.push(` ${s.description}`)
194
230
  }
195
231
  for (const b of schema.bindings || []) lines.push(` ${b.name} [bound to ${b.from}; not settable]`)
@@ -197,7 +233,11 @@ function formatSchema(schema) {
197
233
  }
198
234
 
199
235
  /**
236
+ * @typedef {{ loginMethod: 'email'|'phone', role: 'primary'|'secondary', stage: 'requested'|'provisioning'|'failed'|'allocated'|'ready',
237
+ * failure?: { errorCode: string, message?: string }, reason?: string, guidance: string, next: string|null, retryable: boolean }} LoginMethodReport
238
+ * @typedef {{ activation: string, failure?: { errorCode: string }, guidance: string, next: string|null }} FirstAdminReport
200
239
  * @typedef {{ deploymentId: string, settingsRevision: number,
240
+ * loginMethods?: Array<{ service: string, primaryLoginMethod: string, settingsRevision: number, methods: LoginMethodReport[], firstAdmin: FirstAdminReport }>|null,
201
241
  * pending: { operationId: string, status: string|null, settings: Record<string, string[]> }|null,
202
242
  * modules: Array<{ module: string, ref?: string, revision: string|null, schemaError: string|null, settings: Array<Setting & { value: unknown, source: string, isSet: boolean }> }> }} DeploymentSettings
203
243
  */
@@ -208,6 +248,7 @@ function formatSchema(schema) {
208
248
  */
209
249
  function formatSettings(attrs) {
210
250
  const lines = [`settings revision ${attrs.settingsRevision}`]
251
+ lines.push(...formatLoginMethods(attrs.loginMethods))
211
252
  if (attrs.pending) {
212
253
  const names = Object.entries(attrs.pending.settings).flatMap(([m, list]) => list.map((n) => `${m}.${n}`))
213
254
  lines.push(`pending: operation ${attrs.pending.operationId} (${attrs.pending.status || '—'})${names.length ? ` applying ${names.join(', ')}` : ''}`)
@@ -216,13 +257,44 @@ function formatSettings(attrs) {
216
257
  lines.push(`${m.module} @ ${m.revision || '—'}`)
217
258
  if (m.schemaError) { lines.push(` (no settings schema: ${m.schemaError})`); continue }
218
259
  for (const s of m.settings) {
219
- const marks = [s.updateBehavior === 'create-only' ? 'create-only' : null, s.kind === 'runtime' ? 'runtime' : null].filter(Boolean)
260
+ const marks = [['create-only', 'add-only'].includes(s.updateBehavior) ? s.updateBehavior : null, s.kind === 'runtime' ? 'runtime' : null, s.authority === 'commercial' ? PLAN_MANAGED : null].filter(Boolean)
220
261
  lines.push(` ${s.name} = ${displayValue(s)} (${s.source}${marks.length ? `; ${marks.join(', ')}` : ''})`)
221
262
  }
222
263
  }
223
264
  return lines
224
265
  }
225
266
 
267
+ // How each sign-in method stage reads: only ready is usable sign-in.
268
+ const STAGE_LABELS = { requested: 'accepted, not deployed', provisioning: 'provisioning', failed: 'failed', allocated: 'created, not ready', ready: 'ready' }
269
+ // How the first administrator's activation reads: only signed in proves their sign-in reached them.
270
+ const ACTIVATION_LABELS = { 'not-designated': 'none', 'pending-delivery': 'designated, not sent', sent: 'sent, not signed in yet', 'delivery-failed': 'not delivered', failed: 'failed', activated: 'signed in', unknown: 'unknown' }
271
+
272
+ /**
273
+ * The sign-in methods section of `settings get`: each method's stage apart, why, and what to run next. Absent (email-only:
274
+ * never read) prints nothing; null (could not be read) says it is unknown.
275
+ * @param {DeploymentSettings['loginMethods']} report
276
+ * @returns {string[]}
277
+ */
278
+ function formatLoginMethods(report) {
279
+ if (report === undefined) return []
280
+ if (report === null) return ['sign-in methods: unknown (the control plane could not read them); run `saaslayer settings get` again']
281
+ const lines = []
282
+ for (const state of report) {
283
+ lines.push(`sign-in methods (${state.service}, primary ${state.primaryLoginMethod}; ready is usable sign-in, anything else is not):`)
284
+ for (const m of state.methods) {
285
+ const why = m.reason || (m.failure && m.failure.errorCode)
286
+ const label = `${STAGE_LABELS[m.stage] || m.stage}${why ? ` (${why})` : ''}`
287
+ lines.push(` ${m.loginMethod} ${m.role}: ${label}${m.stage === 'ready' ? '' : ` — ${m.guidance}`}`)
288
+ if (m.next) lines.push(` next: ${m.next}`)
289
+ }
290
+ const admin = state.firstAdmin
291
+ const label = `${ACTIVATION_LABELS[admin.activation] || admin.activation}${admin.failure ? ` (${admin.failure.errorCode})` : ''}`
292
+ lines.push(` first admin: ${label}${admin.activation === 'activated' ? '' : ` — ${admin.guidance}`}`)
293
+ if (admin.next) lines.push(` next: ${admin.next}`)
294
+ }
295
+ return lines
296
+ }
297
+
226
298
  /**
227
299
  * Settings that differ between two deployments. A secret compares set/unset only.
228
300
  * @param {DeploymentSettings} a
@@ -269,4 +341,4 @@ function formatChanges(patch, current) {
269
341
  return lines
270
342
  }
271
343
 
272
- module.exports = { PROTECTED_ENVS, parseSetFlags, readSettingsFile, mergePatches, valueProblem, secretReference, checkPatch, displayValue, formatSchema, formatSettings, diffSettings, formatChanges }
344
+ module.exports = { PROTECTED_ENVS, SETTINGS_SCHEMA_VERSIONS, readableSchema, parseSetFlags, readSettingsFile, mergePatches, valueProblem, secretReference, checkPatch, displayValue, formatSchema, formatSettings, diffSettings, formatChanges }
@@ -0,0 +1,37 @@
1
+ // The region foundation's SMS sending number as its stack reports it (type, ARN, phone number id), its monthly cost line,
2
+ // and the next steps printed once it exists: the setting that points a deployment at it (plan §3 step 5).
3
+ 'use strict'
4
+
5
+ /** What AWS bills for the number while it exists (End User Messaging monthly number lease). */
6
+ const SMS_NUMBER_COST = '~$2/month'
7
+
8
+ /**
9
+ * The installed number type (none | toll-free | simulator) and, when one exists, its ARN and phone number id.
10
+ * @param {{ Parameters?: Array<{ ParameterKey: string, ParameterValue: string }>, Outputs?: Array<{ OutputKey: string, OutputValue: string }> }} stack
11
+ * @returns {{ numberType: string, arn: string|null, phoneNumberId: string|null }}
12
+ */
13
+ function smsNumberOf(stack) {
14
+ const param = (stack.Parameters || []).find((p) => p.ParameterKey === 'SmsOriginationNumberType')
15
+ const output = (stack.Outputs || []).find((o) => o.OutputKey === 'SmsOriginationIdentityArn')
16
+ const arn = output ? output.OutputValue : null
17
+ return { numberType: param ? param.ParameterValue : 'none', arn, phoneNumberId: arn ? arn.split('/').pop() : null }
18
+ }
19
+
20
+ /**
21
+ * Prints what the number can do yet and the exact command that points a deployment at it.
22
+ * @param {(...a: unknown[]) => void} log @param {{ arn: string, env: string, numberType: string }} o
23
+ */
24
+ function logSmsNextSteps(log, { arn, env, numberType }) {
25
+ log(`SMS number: ${arn}`)
26
+ if (numberType === 'simulator') log(' it delivers to AWS simulator destinations only (dev testing; nothing reaches a real phone)')
27
+ else log(` it cannot send until its registration is approved: saaslayer sms register --env ${env} (AWS review: up to 15 business days)`)
28
+ const reason = env === 'staging' || env === 'prod' ? ' --reason "SMS origination for phone login"'
29
+ : env === '<env>' ? ' (staging/prod also take --reason "SMS origination for phone login")' : ''
30
+ log('Point a deployment at it:')
31
+ log(' existing deployment:')
32
+ log(` saaslayer settings set --env ${env} --set user-service.PhoneSmsOriginationIdentity=${arn}${reason}`)
33
+ log(' new deployment:')
34
+ log(` saaslayer deploy --env ${env} --services user-service,permissions-service --set user-service.PhoneSmsOriginationIdentity=${arn}`)
35
+ }
36
+
37
+ module.exports = { SMS_NUMBER_COST, smsNumberOf, logSmsNextSteps }
@@ -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 }