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,109 @@
1
+ // `saaslayer org members list|add|remove|set-role` — an org owner manages who belongs to the org and who deploys. Members
2
+ // are added by account id (`saaslayer whoami` prints it); the control plane refuses accounts whose email is not verified.
3
+ 'use strict'
4
+ const context = require('../context-store')
5
+ const { jsonApiCall } = require('../api-client')
6
+ const prompt = require('../prompt')
7
+
8
+ /**
9
+ * @typedef {{ userId: string, email?: string, owner?: boolean, deployer?: boolean }} MemberRow
10
+ * @typedef {{ ask?: (question: string) => Promise<string> }} ConfirmIo
11
+ */
12
+
13
+ /** @param {Record<string, any>} flags */
14
+ function orgOf(flags) {
15
+ const orgId = flags.org || context.get('org')
16
+ if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
17
+ return String(orgId)
18
+ }
19
+
20
+ /**
21
+ * The account id from --user or the positional argument.
22
+ * @param {Record<string, any>} flags
23
+ * @param {string | undefined} positional
24
+ * @param {string} usage the command, for the error
25
+ * @returns {string}
26
+ */
27
+ function accountOf(flags, positional, usage) {
28
+ const userId = flags.user || positional
29
+ if (!userId || typeof userId !== 'string') throw new Error(`${usage} needs the account id: --user <accountId> (the member finds it with \`saaslayer whoami\`)`)
30
+ return userId
31
+ }
32
+
33
+ const membersPath = (orgId) => `/api/orgs/${encodeURIComponent(orgId)}/members`
34
+
35
+ /** @param {MemberRow} m */
36
+ function roleOf(m) {
37
+ return m.owner ? 'owner' : m.deployer ? 'deployer' : 'member'
38
+ }
39
+
40
+ /**
41
+ * Print and return the org's members.
42
+ * @param {Record<string, any>} flags --org
43
+ * @returns {Promise<MemberRow[]>}
44
+ */
45
+ async function membersList(flags = {}) {
46
+ const orgId = orgOf(flags)
47
+ const doc = await jsonApiCall('GET', membersPath(orgId), undefined, flags)
48
+ /** @type {MemberRow[]} */
49
+ const rows = (doc.data || []).map((d) => d.attributes)
50
+ if (!rows.length) console.log(`no members in ${orgId}`)
51
+ for (const m of rows) console.log(`${m.userId} ${m.email || '—'} ${roleOf(m)}`)
52
+ return rows
53
+ }
54
+
55
+ /**
56
+ * Add an account to the org by its account id (`--role deployer` also lets it deploy). The control plane is asked first
57
+ * which account that id is; its email is shown and must be typed back unless --yes.
58
+ * @param {Record<string, any>} flags --org, --user, --role, --yes
59
+ * @param {ConfirmIo} [io]
60
+ * @param {string} [positional] the account id, when not given as --user
61
+ * @returns {Promise<{ userId: string, email: string, deployer: boolean } | null>} null when aborted
62
+ */
63
+ async function membersAdd(flags = {}, io = {}, positional) {
64
+ const userId = accountOf(flags, positional, 'org members add')
65
+ const role = flags.role
66
+ if (role !== undefined && role !== 'deployer') throw new Error('org members add: --role deployer is the only role an owner grants (omit it for a plain member)')
67
+ const orgId = orgOf(flags)
68
+ const attributes = { userId, ...(role ? { role } : {}) }
69
+ const preview = (await jsonApiCall('POST', membersPath(orgId), { data: { type: 'org-members', attributes: { ...attributes, dryRun: true } } }, flags)).data.attributes
70
+ console.log(`Adding ${preview.email} (${userId}) to org ${orgId}${role ? ' as a deployer' : ''}.`)
71
+ if (!flags.yes) {
72
+ const ask = io.ask || prompt.ask
73
+ const typed = await ask(`Type the account's email "${preview.email}" to confirm: `)
74
+ if (typed.trim().toLowerCase() !== String(preview.email).toLowerCase()) { console.log('Aborted (email did not match).'); return null }
75
+ }
76
+ const added = (await jsonApiCall('POST', membersPath(orgId), { data: { type: 'org-members', attributes } }, flags)).data.attributes
77
+ console.log(`✅ added ${added.email} (${userId}) to ${orgId}${added.deployer ? ' as a deployer' : ''}`)
78
+ return { userId, email: added.email, deployer: Boolean(added.deployer) }
79
+ }
80
+
81
+ /**
82
+ * Remove a member from the org (its deployer role is revoked first).
83
+ * @param {Record<string, any>} flags --org, --user
84
+ * @param {string} [positional]
85
+ */
86
+ async function membersRemove(flags = {}, positional) {
87
+ const userId = accountOf(flags, positional, 'org members remove')
88
+ const orgId = orgOf(flags)
89
+ await jsonApiCall('DELETE', `${membersPath(orgId)}/${encodeURIComponent(userId)}`, undefined, flags)
90
+ console.log(`✅ removed ${userId} from ${orgId}`)
91
+ return { userId, removed: true }
92
+ }
93
+
94
+ /**
95
+ * Make a member a deployer (`--role deployer`) or a plain member again (`--role member`).
96
+ * @param {Record<string, any>} flags --org, --user, --role
97
+ * @param {string} [positional]
98
+ */
99
+ async function membersSetRole(flags = {}, positional) {
100
+ const userId = accountOf(flags, positional, 'org members set-role')
101
+ if (flags.role !== 'deployer' && flags.role !== 'member') throw new Error('org members set-role needs --role deployer|member')
102
+ const orgId = orgOf(flags)
103
+ const path = `${membersPath(orgId)}/${encodeURIComponent(userId)}/roles/deployer`
104
+ await jsonApiCall(flags.role === 'deployer' ? 'POST' : 'DELETE', path, undefined, flags)
105
+ console.log(`✅ ${userId} is now a ${flags.role} of ${orgId}`)
106
+ return { userId, role: flags.role }
107
+ }
108
+
109
+ module.exports = { membersList, membersAdd, membersRemove, membersSetRole }
@@ -0,0 +1,80 @@
1
+ // `saaslayer permissions orgs create|members add|hook-joinable set|disable`: a deployment's runtime orgs through its
2
+ // permissions API — create an org, add a user to it (then `permissions owner bootstrap` makes a member its first owner),
3
+ // and publish which roles one user-service instance's lifecycle hook may grant in it (the org owner, signed in as themselves).
4
+ 'use strict'
5
+ const { exchangeIamToken } = require('../iam-session')
6
+ const { permissionsRequest } = require('../permissions-request')
7
+
8
+ /**
9
+ * @typedef {import('../permissions-request').PermissionsFlags & { id?: string, description?: string, user?: string, email?: string,
10
+ * consumer?: string, role?: string|string[] }} OrgFlags
11
+ * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
12
+ */
13
+
14
+ /** @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
15
+ const resourceOf = (body) => ({ id: body.data.id, ...body.data.attributes })
16
+
17
+ /**
18
+ * Create an org named <name>; --id picks its id (else the API generates one).
19
+ * @param {string[]} positional @param {OrgFlags} flags @param {Deps} [deps]
20
+ */
21
+ async function orgCreate(positional, flags, deps = {}) {
22
+ const label = 'permissions orgs create'
23
+ const name = positional[0]
24
+ if (!name) throw new Error(`${label}: <name> is required`)
25
+ return resourceOf(await permissionsRequest(label, flags, deps, 'POST', '/orgs', {
26
+ ...(flags.id ? { id: String(flags.id) } : {}),
27
+ name,
28
+ ...(flags.description ? { description: String(flags.description) } : {}),
29
+ }))
30
+ }
31
+
32
+ /**
33
+ * Add the user --user <suid> to <orgId>; --email stores a profile copy for member lists.
34
+ * @param {string[]} positional @param {OrgFlags} flags @param {Deps} [deps]
35
+ */
36
+ async function orgMemberAdd(positional, flags, deps = {}) {
37
+ const label = 'permissions orgs members add'
38
+ const orgId = positional[0]
39
+ if (!orgId) throw new Error(`${label}: <orgId> is required`)
40
+ if (!flags.user) throw new Error(`${label}: --user <suid> is required`)
41
+ return resourceOf(await permissionsRequest(label, flags, deps, 'POST', `/orgs/${encodeURIComponent(orgId)}/members`, {
42
+ type: 'user',
43
+ id: String(flags.user),
44
+ ...(flags.email ? { email: String(flags.email) } : {}),
45
+ }))
46
+ }
47
+
48
+ /** The org and the hookJoinable policy it now publishes. @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
49
+ const policyOf = (body) => ({ id: body.data.id, hookJoinable: body.data.attributes.hookJoinable })
50
+
51
+ /**
52
+ * Publish <orgId>'s hookJoinable policy: the exact roles (--role, repeatable) the lifecycle hook of one user-service
53
+ * instance (--consumer user-service@<deploymentId>/<instance>) may grant in the org. The API refuses anyone but an owner
54
+ * of the org signed in as themselves (403), and privileged or unknown roles (400).
55
+ * @param {string[]} positional @param {OrgFlags} flags @param {Deps} [deps]
56
+ */
57
+ async function orgHookJoinableSet(positional, flags, deps = {}) {
58
+ const label = 'permissions orgs hook-joinable set'
59
+ const orgId = positional[0]
60
+ if (!orgId) throw new Error(`${label}: <orgId> is required`)
61
+ if (typeof flags.consumer !== 'string' || !flags.consumer) throw new Error(`${label}: --consumer <user-service@<deploymentId>/<instance>> is required`)
62
+ const roles = (flags.role === undefined ? [] : [].concat(flags.role)).filter((r) => typeof r === 'string' && r)
63
+ if (!roles.length) throw new Error(`${label}: at least one --role <roleId> is required`)
64
+ return policyOf(await permissionsRequest(label, flags, deps, 'PUT', `/orgs/${encodeURIComponent(orgId)}`, {
65
+ hookJoinable: { enabled: true, consumer: flags.consumer, roles },
66
+ }))
67
+ }
68
+
69
+ /**
70
+ * Stop <orgId>'s hooks from granting any role in it ({ hookJoinable: { enabled: false } }). Owner only, as for set.
71
+ * @param {string[]} positional @param {OrgFlags} flags @param {Deps} [deps]
72
+ */
73
+ async function orgHookJoinableDisable(positional, flags, deps = {}) {
74
+ const label = 'permissions orgs hook-joinable disable'
75
+ const orgId = positional[0]
76
+ if (!orgId) throw new Error(`${label}: <orgId> is required`)
77
+ return policyOf(await permissionsRequest(label, flags, deps, 'PUT', `/orgs/${encodeURIComponent(orgId)}`, { hookJoinable: { enabled: false } }))
78
+ }
79
+
80
+ module.exports = { orgCreate, orgMemberAdd, orgHookJoinableSet, orgHookJoinableDisable }
@@ -7,6 +7,7 @@ const { finishMutation, requestKeyHeaders } = require('./operations')
7
7
  const { applySettings, fetchSchema, readDeploymentSettings } = require('./settings')
8
8
  const { formatChanges } = require('../settings')
9
9
  const rm = require('../release-manifest')
10
+ const { checkReleaseChoice } = require('../versions')
10
11
  const { version: CLI_VERSION } = require('../../package.json')
11
12
 
12
13
  const USAGE = 'usage: saaslayer release-manifest create --env E [--out FILE] [--name NAME] (see saaslayer --help)'
@@ -41,6 +42,7 @@ async function updateFromManifest(flags) {
41
42
  if (flags['commit-sha'] !== undefined || flags.commitSha !== undefined || flags.param !== undefined) {
42
43
  throw new Error('--manifest sets the release and settings: drop --commit-sha and --param')
43
44
  }
45
+ if (flags.version !== undefined || flags.channel !== undefined) throw new Error('--manifest sets the release and settings: drop --version and --channel')
44
46
  const file = flags.manifest
45
47
  if (typeof file !== 'string') throw new Error('update --manifest needs a release manifest file')
46
48
  const manifest = rm.readManifest(file)
@@ -58,13 +60,17 @@ async function updateFromManifest(flags) {
58
60
  noWait: flagOn(flags, 'no-wait'),
59
61
  })
60
62
  const target = manifest.bundle.revision
63
+ // A versioned manifest moves by version (checked against the control plane first); its revision is the commit the
64
+ // contracts above were checked at.
65
+ const version = manifest.bundle.version
66
+ const targetLabel = version ? `${version} (${target.slice(0, 7)})` : target.slice(0, 7)
61
67
  const where = `${env} (${deployment.deploymentId})`
62
68
  if (!result.ok) {
63
69
  const lines = result.problems.map((p) => ` - ${p.code}: ${p.message}${p.action ? `\n → ${p.action}` : ''}`)
64
70
  throw new Error(`preflight ${where} failed — nothing was changed:\n${lines.join('\n')}`)
65
71
  }
66
72
  console.log(`preflight ${where}: ok${manifest.name ? ` (${manifest.name})` : ''}`)
67
- console.log(` release: ${result.fromRevisions.map((r) => r.slice(0, 7)).join(', ')} → ${target.slice(0, 7)}${result.moveRelease ? '' : ' (already deployed)'}`)
73
+ console.log(` release: ${result.fromRevisions.map((r) => r.slice(0, 7)).join(', ')} → ${targetLabel}${result.moveRelease ? '' : ' (already deployed)'}`)
68
74
  if (result.patch) for (const line of formatChanges(result.patch, settings)) console.log(line)
69
75
  else console.log(` settings: ${envPatch ? 'match' : `none named for ${env}`}`)
70
76
  if (flagOn(flags, 'dry-run')) {
@@ -72,15 +78,16 @@ async function updateFromManifest(flags) {
72
78
  return result
73
79
  }
74
80
  if (!result.moveRelease && !result.patch) {
75
- console.log(`${deployment.deploymentId} already runs ${target.slice(0, 7)} and its settings match: nothing to change`)
81
+ console.log(`${deployment.deploymentId} already runs ${targetLabel} and its settings match: nothing to change`)
76
82
  return result
77
83
  }
78
84
  if (result.moveRelease) {
79
- const attributes = { commitSha: target }
85
+ const attributes = version ? { version } : { commitSha: target }
86
+ if (version) await checkReleaseChoice({ version }, flags)
80
87
  if (flags.reason) attributes.reason = flags.reason
81
88
  if (flagOn(flags, 'force')) attributes.force = true
82
89
  const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
83
- console.log(`✅ release move to ${target.slice(0, 7)} started for ${deployment.deploymentId}`)
90
+ console.log(`✅ release move to ${version || target.slice(0, 7)} started for ${deployment.deploymentId}`)
84
91
  await finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
85
92
  }
86
93
  if (result.patch) await applySettings(result.patch, flags)
@@ -88,8 +95,9 @@ async function updateFromManifest(flags) {
88
95
  }
89
96
 
90
97
  /**
91
- * `release-manifest create --env E [--out FILE] [--name NAME]`: the revision, settings-contract hashes and permissions writer
92
- * declaration of a tested deployment, and this CLI's version. Reader declarations and environment settings are left
98
+ * `release-manifest create --env E [--out FILE] [--name NAME]`: the version and revision, settings-contract hashes and
99
+ * permissions writer declaration of a tested deployment, and this CLI's version. A deployment on an unversioned commit
100
+ * is refused: a manifest moves by version. Reader declarations and environment settings are left
93
101
  * for the author: a missing reader declaration is never inferred.
94
102
  * @param {object} flags
95
103
  */
@@ -100,6 +108,7 @@ async function createManifest(flags) {
100
108
  throw new Error(`${deployment.deploymentId} runs more than one revision (${settings.modules.map((m) => `${m.module}@${(m.revision || '—').slice(0, 7)}`).join(', ')}): update it to one tested release first`)
101
109
  }
102
110
  const revision = /** @type {string} */ (revisions[0])
111
+ if (!deployment.version) throw new Error(`${deployment.deploymentId} runs an unversioned release (${revision.slice(0, 7)}): move it to a version first (saaslayer versions lists them)`)
103
112
  /** @type {Record<string, { settingsContractSha256: string }>} */
104
113
  const modules = {}
105
114
  for (const m of settings.modules) modules[m.module] = { settingsContractSha256: rm.contractHash(await fetchSchema(m.module, revision, flags)) }
@@ -108,7 +117,7 @@ async function createManifest(flags) {
108
117
  const manifest = {
109
118
  schemaVersion: rm.MANIFEST_SCHEMA_VERSION,
110
119
  ...(typeof flags.name === 'string' ? { name: flags.name } : {}),
111
- bundle: { revision, modules },
120
+ bundle: { revision, version: deployment.version, modules },
112
121
  tooling: { cli: CLI_VERSION },
113
122
  ...(writer ? { compatibility: { permissions: rm.permissionsWriterRelease(docSetting ? docSetting.value : undefined) } } : {}),
114
123
  environments: {},
@@ -118,7 +127,7 @@ async function createManifest(flags) {
118
127
  const text = `${JSON.stringify(manifest, null, 2)}\n`
119
128
  if (typeof flags.out === 'string') {
120
129
  fs.writeFileSync(flags.out, text)
121
- console.log(`release manifest for ${deployment.deploymentId} @ ${revision.slice(0, 7)} written to ${flags.out}`)
130
+ console.log(`release manifest for ${deployment.deploymentId} @ ${deployment.version} (${revision.slice(0, 7)}) written to ${flags.out}`)
122
131
  } else {
123
132
  console.log(text)
124
133
  }
@@ -1,11 +1,13 @@
1
- // `saaslayer permissions service-principal roles|assign|unassign`: typed role assignment for service principals (matrix R10)
2
- // — a declared IAM machine's mapped principal (--machine <principalId> → iam.<principalId>) or any service account id.
1
+ // `saaslayer permissions service-principal roles|assign|unassign|verifier-key create`: typed role assignment for service
2
+ // principals (matrix R10) — a declared IAM machine's mapped principal (--machine <principalId> → iam.<principalId>) or any
3
+ // service account id — and verify-only API keys for a customer backend's service account.
3
4
  'use strict'
4
- const { exchangeIamToken } = require('../iam-session')
5
+ const { exchangeIamToken, awsCredentials } = require('../iam-session')
5
6
  const { authHeaders } = require('../deployment-api-auth')
7
+ const { ssmApi } = require('../ssm-api')
6
8
 
7
9
  /**
8
- * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, machine?: string, role?: string, scope?: string }} ServicePrincipalFlags
10
+ * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, machine?: string, role?: string, scope?: string, 'ssm-parameter'?: string }} ServicePrincipalFlags
9
11
  */
10
12
 
11
13
  /**
@@ -78,4 +80,39 @@ async function servicePrincipalUnassign(positional, flags, deps = {}) {
78
80
  await call('permissions service-principal unassign', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles/${encodeURIComponent(flags.role)}${qs}`, { method: 'DELETE', headers: auth })
79
81
  }
80
82
 
81
- module.exports = { servicePrincipalRoles, servicePrincipalAssign, servicePrincipalUnassign }
83
+ /**
84
+ * Issue a service principal a deployment-wide key whose only permission is verifying API keys (created, owned by the
85
+ * caller, when missing). The secret is returned only by this call.
86
+ * @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
87
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
88
+ * @returns {Promise<{ keyId: string, apiKey: string, servicePrincipalId: string, expiresAt: string|null }>}
89
+ */
90
+ async function verifierKeyCreate(positional, flags, deps = {}) {
91
+ const { id, apiBase } = target('permissions service-principal verifier-key create', positional, flags)
92
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
93
+ const body = await call('permissions service-principal verifier-key create', `${apiBase}/service-principals/${encodeURIComponent(id)}/verifier-keys`, {
94
+ method: 'POST',
95
+ headers: { ...auth, 'content-type': 'application/json' },
96
+ body: JSON.stringify({}),
97
+ })
98
+ const { attributes } = body.data
99
+ return { keyId: body.data.id, apiKey: attributes.apiKey, servicePrincipalId: attributes.servicePrincipal.id, expiresAt: attributes.expiresAt || null }
100
+ }
101
+
102
+ /**
103
+ * Write a verifier key to the SecureString --ssm-parameter (replacing the key it held), with the caller's AWS credentials
104
+ * (--profile) in --region (default $AWS_REGION).
105
+ * @param {string} apiKey @param {ServicePrincipalFlags} flags
106
+ * @param {{ credentials?: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, fetch?: typeof fetch }} [deps]
107
+ * @returns {Promise<{ name: string, version: number }>}
108
+ */
109
+ async function storeVerifierKey(apiKey, flags, deps = {}) {
110
+ const name = String(flags['ssm-parameter'])
111
+ const region = flags.region || process.env.AWS_REGION
112
+ if (!region) throw new Error('permissions service-principal verifier-key create: --region (or $AWS_REGION) is required with --ssm-parameter')
113
+ const put = ssmApi({ region, credentials: deps.credentials || (() => awsCredentials({ profile: flags.profile })), fetchImpl: deps.fetch || fetch })
114
+ const doc = await put('PutParameter', { Name: name, Value: apiKey, Type: 'SecureString', Overwrite: true, Description: 'SaaSLayer verifier API key (keys:api-key:verify only)' })
115
+ return { name, version: doc.Version }
116
+ }
117
+
118
+ module.exports = { servicePrincipalRoles, servicePrincipalAssign, servicePrincipalUnassign, verifierKeyCreate, storeVerifierKey }
@@ -4,9 +4,11 @@
4
4
  const { apiCall } = require('../api-client')
5
5
  const { resolveDeployment } = require('../deployments')
6
6
  const { finishMutation, requestKeyHeaders } = require('./operations')
7
- const { parseSetFlags, readSettingsFile, mergePatches, checkPatch, formatSchema, formatSettings, formatChanges, PROTECTED_ENVS } = require('../settings')
7
+ const { parseSetFlags, readSettingsFile, mergePatches, checkPatch, formatSchema, formatSettings, formatChanges, readableSchema, PROTECTED_ENVS } = require('../settings')
8
8
  const { readManifest, environmentSettings } = require('../release-manifest')
9
9
  const { compareEnvironments, formatComparison } = require('../env-compare')
10
+ const { refuseManagedLoginDomainSettings, admitLoginDomainChanges, loginDomainChecklist } = require('../login-domain')
11
+ const { USER_SERVICE, signInChange, signInRefusalHint } = require('../login-methods')
10
12
 
11
13
  const USAGE = 'usage: saaslayer settings <schema|get|set|diff> … (see saaslayer --help)'
12
14
 
@@ -39,7 +41,7 @@ async function readDeploymentSettings(flags) {
39
41
  */
40
42
  async function fetchSchema(module, revision, flags) {
41
43
  const doc = await apiCall('GET', `/api/modules/${encodeURIComponent(module)}/settings-schema?revision=${encodeURIComponent(revision)}`, undefined, flags)
42
- return doc.data.attributes
44
+ return readableSchema(doc.data.attributes)
43
45
  }
44
46
 
45
47
  /** `settings schema --module M [--revision SHA]`; without --revision, the revision the selected deployment runs. @param {object} flags */
@@ -74,26 +76,40 @@ async function settingsGet(flags) {
74
76
  async function applySettings(input, flags) {
75
77
  const { deployment, settings } = await readDeploymentSettings(flags)
76
78
  const schemas = Object.fromEntries(settings.modules.filter((m) => !m.schemaError).map((m) => [m.module, { module: m.module, revision: m.revision, settings: m.settings }]))
77
- const { patch, billing } = checkPatch(input, schemas, { op: 'update' })
79
+ const current = Object.fromEntries(settings.modules.map((m) => [m.module, Object.fromEntries(m.settings.map((s) => [s.name, s]))]))
80
+ const { patch, billing, security } = checkPatch(input, schemas, { op: 'update', current })
81
+ refuseManagedLoginDomainSettings(patch)
82
+ const signIn = patch[USER_SERVICE] ? signInChange({ op: 'update', values: patch[USER_SERVICE], current: current[USER_SERVICE], env: deployment.env }) : null
83
+ if (signIn && signIn.problems.length) throw new Error(signIn.problems.join('\n'))
78
84
  const reason = typeof flags.reason === 'string' ? flags.reason : undefined
85
+ if (!reason && signIn && signIn.added.length) throw new Error(`${USER_SERVICE} adds ${signIn.added.map((a) => a.loginMethod).join(' and ')} sign-in, which cannot be turned off and has costs: pass --reason <text>`)
79
86
  if (!reason && billing.length) throw new Error(`${billing.join(', ')} changes billing: pass --reason <text>`)
87
+ if (!reason && security.length) throw new Error(`${security.join(', ')} changes security: pass --reason <text>`)
80
88
  if (!reason && PROTECTED_ENVS.has(deployment.env)) throw new Error(`${deployment.env} is a protected environment: pass --reason <text>`)
89
+ const { domainHandoff, handoffs } = await admitLoginDomainChanges({ patch, settings, deploymentId: deployment.deploymentId, flags })
81
90
  console.log(`Changing settings of ${deployment.deploymentId} (settings revision ${settings.settingsRevision}):`)
82
91
  for (const line of formatChanges(patch, settings)) console.log(line)
83
- const attributes = { expectedRevision: settings.settingsRevision, settings: patch, ...(reason ? { reason } : {}) }
92
+ for (const line of signIn ? signIn.preview : []) console.log(` ${line}`)
93
+ const attributes = { expectedRevision: settings.settingsRevision, settings: patch, ...(reason ? { reason } : {}), ...(domainHandoff ? { domainHandoff } : {}) }
84
94
  let res
85
95
  try {
86
96
  res = await apiCall('PATCH', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, { data: { type: 'deployment-settings', attributes } }, flags, { headers: requestKeyHeaders() })
87
97
  } catch (err) {
88
98
  if (err.status === 409) err.message += `\nthe settings changed after they were read (revision ${settings.settingsRevision}): check them with \`saaslayer settings get\` and run the command again`
99
+ const hint = signInRefusalHint(err, deployment.env)
100
+ if (hint) err.message += `\n${hint}`
89
101
  throw err
90
102
  }
91
103
  const written = res.data.attributes
92
104
  console.log(`✅ settings revision ${settings.settingsRevision} → ${written.settingsRevision} (operation ${written.operationId})`)
105
+ if (handoffs.length > 0) {
106
+ console.log('Login domain handoff: the confirmation acknowledges what breaks; finish each step:')
107
+ for (const line of loginDomainChecklist(handoffs)) console.log(line)
108
+ }
93
109
  return finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
94
110
  }
95
111
 
96
- /** `settings set --env E (--set M.S=V … | --file F) [--reason T]`. @param {object} flags */
112
+ /** `settings set --env E (--set M.S=V … | --file F) [--reason T] [--domain-handoff --confirm-domain D]`. @param {object} flags */
97
113
  async function settingsSet(flags) {
98
114
  const patch = mergePatches(typeof flags.file === 'string' ? readSettingsFile(flags.file) : undefined, parseSetFlags(flags.set, '--set'))
99
115
  if (!patch) throw new Error('settings set needs --set <module>.<Setting>=<value> or --file <settings.json>')
@@ -0,0 +1,182 @@
1
+ // `saaslayer sms register` and `saaslayer sms status` (cloud-prem): register the foundation's toll-free number with
2
+ // AWS from prompts or registration.json, and show what still stands between the account and delivered SMS.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const { execFileSync } = require('child_process')
7
+ const { jsonApiCall } = require('../api-client')
8
+ const { ask: promptAsk } = require('../prompt')
9
+ const { describeStack } = require('../foundation-change-set')
10
+ const { foundationRegionStackName } = require('./aws')
11
+ const { cloudPremTarget } = require('../sms/scope')
12
+ const { smsNumberOf } = require('../sms/number')
13
+ const { recordLandedRelease } = require('../sms/release')
14
+ const { resolveFields, isRequired, answerAt, withAnswer, answersFromValues } = require('../sms/registration-fields')
15
+ const { validateRegistration } = require('../sms/registration-validate')
16
+ const sms = require('../sms/registration')
17
+ const { smsStatusReport, formatSmsStatus } = require('../sms/status')
18
+
19
+ /**
20
+ * @typedef {{ api?: typeof jsonApiCall, exec?: (cmd: string, args: string[]) => string, sms?: import('../sms/registration').SmsClient,
21
+ * fetch?: import('../sms/registration-validate').Fetch, ask?: (q: string) => Promise<string>, interactive?: boolean,
22
+ * cwd?: string, sleep?: (ms: number) => Promise<void>, log?: (...a: unknown[]) => void, err?: (...a: unknown[]) => void }} Deps
23
+ */
24
+
25
+ /** @param {string} cmd @param {string[]} args */
26
+ const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 })
27
+ const REVIEW_TIME = 'AWS review takes up to 15 business days'
28
+
29
+ /**
30
+ * The account, region and sending number a command acts on, after the cloud-prem checks.
31
+ * @param {Record<string, any>} flags @param {string} command @param {Required<Pick<Deps, 'api'|'exec'|'err'>> & Deps} d
32
+ */
33
+ async function smsContext(flags, command, d) {
34
+ const { target, aws } = await cloudPremTarget(flags, command, { api: d.api, exec: d.exec, log: d.err })
35
+ const stack = describeStack(aws, foundationRegionStackName(target.region))
36
+ const arn = stack ? smsNumberOf(stack).arn : null
37
+ const client = d.sms || sms.createSmsClient({ region: target.region, profile: flags.profile })
38
+ return { target, stack, arn, client }
39
+ }
40
+
41
+ /** @param {Deps} deps */
42
+ function withDefaults(deps) {
43
+ return {
44
+ api: jsonApiCall, exec: defaultExec, fetch: globalThis.fetch, ask: promptAsk, interactive: Boolean(process.stdin.isTTY),
45
+ cwd: process.cwd(), sleep: (ms) => new Promise((r) => setTimeout(r, ms)), log: console.log, err: console.error, ...deps,
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Ask for each field's answer; Enter keeps the shown value; a required field is asked again until answered.
51
+ * @param {import('../sms/registration-fields').ResolvedField[]} fields @param {object} current @param {(q: string) => Promise<string>} ask
52
+ */
53
+ async function promptAnswers(fields, current, ask) {
54
+ let answers = current
55
+ for (const field of fields) {
56
+ if (field.derive) continue
57
+ const shown = answerAt(current, field.key)
58
+ const options = field.type === 'SELECT' && field.key !== 'monthlyVolume' ? ` (choices: ${((field.definition.SelectValidation || {}).Options || []).join(', ')})` : ''
59
+ const hint = field.type === 'ATTACHMENT' ? ' (PNG file or https URL)' : field.key === 'monthlyVolume' ? ' (messages per month)' : ''
60
+ for (;;) {
61
+ const required = isRequired(field, answers)
62
+ const reply = await ask(`${field.title}${required ? '' : ' (optional)'}${options}${hint}${shown !== undefined ? ` [${shown}]` : ''}: `)
63
+ const value = reply === '' ? shown : reply
64
+ if ((value === undefined || value === '') && required) continue
65
+ if (value !== undefined && value !== '') answers = withAnswer(answers, field.key, field.key === 'monthlyVolume' ? Number(String(value).replace(/[^0-9]/g, '')) : value)
66
+ break
67
+ }
68
+ }
69
+ return answers
70
+ }
71
+
72
+ /**
73
+ * The answers for `fields`: from --file (only those fields' keys are taken) or asked in a terminal.
74
+ * @param {Record<string, any>} flags @param {import('../sms/registration-fields').ResolvedField[]} fields @param {object} current
75
+ * @param {ReturnType<typeof withDefaults>} d
76
+ */
77
+ async function collectAnswers(flags, fields, current, d) {
78
+ if (typeof flags.file === 'string') {
79
+ const file = path.resolve(d.cwd, flags.file)
80
+ let doc
81
+ try { doc = JSON.parse(fs.readFileSync(file, 'utf8')) } catch (e) { throw new Error(`cannot read ${file} as JSON: ${e.message}`) }
82
+ let answers = current
83
+ for (const field of fields) {
84
+ const value = answerAt(doc, field.key)
85
+ if (value !== undefined) answers = withAnswer(answers, field.key, value)
86
+ }
87
+ // The file's samples list replaces the current one when samples are being written.
88
+ if (fields.some((f) => f.key.startsWith('samples.')) && Array.isArray(doc.samples)) answers = withAnswer(answers, 'samples', doc.samples)
89
+ return { answers, cwd: path.dirname(file) }
90
+ }
91
+ if (!d.interactive) throw new Error('sms register needs answers: pass --file registration.json when not running in a terminal')
92
+ return { answers: await promptAnswers(fields, current, d.ask), cwd: d.cwd }
93
+ }
94
+
95
+ /** @param {Array<Record<string, any>>} reasons @param {(...a: unknown[]) => void} log */
96
+ function logReasons(reasons, log) {
97
+ for (const r of reasons) log(` ${r.Reason}: ${r.ShortDescription || ''}${r.DocumentationLink ? ` (${r.DocumentationLink})` : ''}`)
98
+ }
99
+
100
+ /**
101
+ * `saaslayer sms register --env <env> [--file registration.json]`: create or resume the number's toll-free registration,
102
+ * validate and fill it, attach the opt-in evidence, associate the number and submit; resubmit after REQUIRES_UPDATES.
103
+ * @param {Record<string, any>} flags @param {Deps} [deps]
104
+ * @returns {Promise<{ registrationId: string|null, status: string|null, changed: boolean }>}
105
+ */
106
+ async function smsRegister(flags, deps = {}) {
107
+ const d = withDefaults(deps)
108
+ const { target, arn, client } = await smsContext(flags, 'sms register', d)
109
+ if (!arn) throw new Error(`no SMS sending number in account ${target.accountId} (${target.region}): run \`saaslayer sms setup --env ${target.env}\` first`)
110
+ const number = await sms.describeNumber(client, arn)
111
+ if (number.NumberType === 'SIMULATOR') {
112
+ d.log(`${number.PhoneNumberId} is a simulator number; it needs no registration (it delivers to simulator destinations only)`)
113
+ return { registrationId: null, status: null, changed: false }
114
+ }
115
+
116
+ const { registration: found, ended } = await sms.findRegistration(client, number)
117
+ if (found && !sms.EDITABLE_STATUSES.includes(found.RegistrationStatus)) {
118
+ d.log(`${found.RegistrationId} is ${found.RegistrationStatus}; nothing to change. Check progress with \`saaslayer sms status --env ${target.env}\`.`)
119
+ return { registrationId: found.RegistrationId, status: found.RegistrationStatus, changed: false }
120
+ }
121
+ const fields = resolveFields(await sms.fieldDefinitions(client))
122
+
123
+ let version = found ? found.CurrentVersionNumber : 1
124
+ let toWrite = fields
125
+ let current = found ? await sms.fieldValues(client, found.RegistrationId, version) : []
126
+ let needsVersion = false
127
+ if (found && found.RegistrationStatus === 'REQUIRES_UPDATES') {
128
+ const id = found.RegistrationId
129
+ const denied = found.LatestDeniedVersionNumber || version
130
+ const deniedVersion = await sms.describeVersion(client, id, denied)
131
+ const deniedValues = await sms.fieldValues(client, id, denied)
132
+ d.log(`AWS sent ${id} back for updates (version ${denied}):`)
133
+ logReasons((deniedVersion && deniedVersion.DeniedReasons) || [], d.log)
134
+ const flagged = deniedValues.filter((v) => v.DeniedReason)
135
+ for (const v of flagged) {
136
+ const field = fields.find((f) => f.path === v.FieldPath)
137
+ d.log(` ${field ? `${field.key} (${field.title})` : v.FieldPath}: ${v.DeniedReason}`)
138
+ }
139
+ // Only the flagged fields are asked again; with none flagged, every field is.
140
+ const flaggedPaths = flagged.map((v) => v.FieldPath)
141
+ toWrite = flaggedPaths.length ? fields.filter((f) => flaggedPaths.includes(f.path)) : fields
142
+ current = deniedValues
143
+ const latest = await sms.describeVersion(client, id, version)
144
+ needsVersion = !latest || latest.RegistrationVersionStatus !== 'DRAFT'
145
+ }
146
+
147
+ // Every answer is checked before anything (the registration included) is written.
148
+ const { answers, cwd } = await collectAnswers(flags, toWrite.filter((f) => !f.derive), answersFromValues(fields, current), d)
149
+ const checked = await validateRegistration(answers, toWrite, { fetch: d.fetch, cwd })
150
+ if (checked.errors.length) throw new Error(`registration answers need fixing (nothing was sent to AWS):\n ${checked.errors.join('\n ')}`)
151
+
152
+ const registration = found || (await sms.createRegistration(client, number, ended))
153
+ const id = registration.RegistrationId
154
+ d.log(`${found ? 'resuming' : 'created'} registration ${id} (${registration.RegistrationStatus}) for ${number.PhoneNumber || number.PhoneNumberId}`)
155
+ if (needsVersion) {
156
+ version = (await sms.newVersion(client, id)).VersionNumber
157
+ current = await sms.fieldValues(client, id, version)
158
+ }
159
+ const attachmentId = checked.attachment ? await sms.uploadAttachment(client, checked.attachment, number.PhoneNumberId, d.sleep) : null
160
+ const written = await sms.writeFields(client, id, toWrite, answers, { attachmentId, current: needsVersion ? current.map(({ DeniedReason, ...v }) => v) : current })
161
+ if (await sms.ensureAssociation(client, id, number)) d.log(`associated ${number.PhoneNumber || number.PhoneNumberId} with ${id}`)
162
+ const submitted = await sms.submitVersion(client, id)
163
+ d.log(`submitted ${id} version ${submitted.VersionNumber || version} (${written.length} field(s) written); ${REVIEW_TIME}. Check progress with \`saaslayer sms status --env ${target.env}\`.`)
164
+ return { registrationId: id, status: submitted.RegistrationVersionStatus || 'SUBMITTED', changed: true }
165
+ }
166
+
167
+ /**
168
+ * `saaslayer sms status --env <env> [--json]`: number, registration, sandbox/production, spend limit, what is missing
169
+ * (as readiness codes) and the support requests AWS has no API for. An unfinished release is moved forward as far as the
170
+ * stack's actual state allows (plan §5 step 5) and shown with the command that resumes it.
171
+ * @param {Record<string, any>} flags @param {Deps} [deps]
172
+ */
173
+ async function smsStatus(flags, deps = {}) {
174
+ const d = withDefaults(deps)
175
+ const { target, stack, arn, client } = await smsContext(flags, 'sms status', d)
176
+ const release = await recordLandedRelease({ api: d.api, target, flags, stack })
177
+ const report = await smsStatusReport({ target, arn, sms: client, release })
178
+ d.log(flags.json ? JSON.stringify(report, null, 2) : formatSmsStatus(report).join('\n'))
179
+ return report
180
+ }
181
+
182
+ module.exports = { smsRegister, smsStatus }