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,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
  }
@@ -1,12 +1,13 @@
1
- // One call to a deployment's permissions API from a CLI command: resolves --api-base (or $SAASLAYER_API_BASE), the selected auth
2
- // (deployment login, API key or IAM), and throws with the API's error codes and messages.
1
+ // One call to a deployment's permissions API from a CLI command: resolves --api-base (or $SAASLAYER_API_BASE) and the selected
2
+ // auth (deployment login, API key, IAM, or an external ID token to a pinned host), and throws with the API's error codes.
3
3
  'use strict'
4
4
  const { exchangeIamToken } = require('./iam-session')
5
- const { authHeaders } = require('./deployment-api-auth')
5
+ const { authHeaders, idTokenTarget } = require('./deployment-api-auth')
6
6
 
7
7
  /**
8
- * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string }} PermissionsFlags
9
- * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
8
+ * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string,
9
+ * 'id-token-file'?: string, yes?: boolean }} PermissionsFlags
10
+ * @typedef {{ exchange?: typeof exchangeIamToken } & import('./deployment-api-auth').IdTokenDeps} Deps
10
11
  */
11
12
 
12
13
  /**
@@ -25,17 +26,22 @@ function apiBaseOf(label, flags) {
25
26
  * @returns {Promise<any>} the response document
26
27
  */
27
28
  async function permissionsRequest(label, flags, deps, method, path, body) {
28
- const apiBase = apiBaseOf(label, flags)
29
- const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
29
+ const pinned = await idTokenTarget(flags, deps)
30
+ const apiBase = pinned ? pinned.apiBase : apiBaseOf(label, flags)
31
+ const auth = pinned ? pinned.headers : await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
30
32
  const res = await fetch(`${apiBase}${path}`, {
31
33
  method,
32
34
  headers: body ? { ...auth, 'content-type': 'application/json' } : auth,
33
35
  ...(body ? { body: JSON.stringify(body) } : {}),
36
+ // The ID token goes only to its pinned host: a redirect would resend it wherever the 3xx points, so none is followed.
37
+ ...(pinned ? { redirect: /** @type {RequestRedirect} */ ('error') } : {}),
34
38
  })
35
39
  const json = await res.json().catch(() => ({}))
36
40
  if (!res.ok) {
37
- const detail = ((json && json.errors) || []).map((/** @type {{ code?: string, message?: string, detail?: string }} */ e) => [e.code, e.message || e.detail].filter(Boolean).join(': ')).join('; ') || JSON.stringify(json)
38
- throw new Error(`${label} failed (${res.status}${detail ? ` ${detail}` : ''})`)
41
+ /** @type {Array<{ code?: string, message?: string, detail?: string }>} */
42
+ const errors = (json && json.errors) || []
43
+ const detail = errors.map((e) => [e.code, e.message || e.detail].filter(Boolean).join(': ')).join('; ') || JSON.stringify(json)
44
+ throw Object.assign(new Error(`${label} failed (${res.status}${detail ? ` ${detail}` : ''})`), { status: res.status, codes: errors.map((e) => e.code).filter(Boolean) })
39
45
  }
40
46
  return json
41
47
  }
@@ -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 }