saaslayer 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +199 -18
  2. package/bin/saaslayer.js +335 -62
  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 +49 -11
  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 +14 -2
  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 +138 -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/bootstrap/saaslayer-bootstrap-permission-set-inline-policy.json +148 -0
  60. package/templates/bootstrap/saaslayer-bootstrap-policy-email-sender.json +22 -0
  61. package/templates/bootstrap/saaslayer-bootstrap-policy-sms-number.json +22 -0
  62. package/templates/bootstrap/saaslayer-bootstrap-policy.json +114 -0
  63. package/templates/bootstrap/saaslayer-bootstrap-trust-policy.json +18 -0
  64. package/templates/saaslayer-foundation-region.yml +45 -1
  65. package/templates/saaslayer-foundation.yml +759 -309
@@ -3,14 +3,16 @@
3
3
  // waits for the resulting operation. destroy + service-remove (delete custody) are guarded: destroy needs a typed
4
4
  // project-name confirmation; a protected-env service removal needs --reason and the typed service name.
5
5
  'use strict'
6
- const { apiCall } = require('../api-client')
6
+ const { apiCall, jsonApiCall } = require('../api-client')
7
7
  const { resolveDeployment } = require('../deployments')
8
8
  const { resolveScope, printScope, deployedProjectsHint } = require('../scope')
9
9
  const { ask } = require('../prompt')
10
10
  const { finishMutation, requestKeyHeaders } = require('./operations')
11
11
  const { fetchModuleCatalog, checkParamModules } = require('../module-catalog')
12
- const { PROTECTED_ENVS, parseSetFlags } = require('../settings')
13
- const { applySettings } = require('./settings')
12
+ const { PROTECTED_ENVS, parseSetFlags, readSettingsFile, mergePatches, checkPatch } = require('../settings')
13
+ const { applySettings, fetchSchema } = require('./settings')
14
+ const { signInRefusalHint } = require('../login-methods')
15
+ const { releaseChoice, checkReleaseChoice, describeChoice } = require('../versions')
14
16
 
15
17
  async function status(flags) {
16
18
  const scope = resolveScope(flags, { env: 'all' })
@@ -29,35 +31,42 @@ async function status(flags) {
29
31
  for (const g of groups) {
30
32
  for (const i of g.instances || []) {
31
33
  const inst = i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''
32
- // release = the commit the instance was last deployed at; a fleet state other than ACTIVE (e.g. migrations
33
- // awaiting approval) is shown because the deployment status alone reads ACTIVE.
34
- const release = i.commitSha ? String(i.commitSha).slice(0, 8) : '—'
34
+ // release = the version the instance runs, else the commit it was last deployed at; a fleet state other than
35
+ // ACTIVE (e.g. migrations awaiting approval) is shown because the deployment status alone reads ACTIVE.
36
+ const release = i.version || (i.commitSha ? String(i.commitSha).slice(0, 8) : '—')
35
37
  const fleet = i.fleetState && i.fleetState !== 'ACTIVE' ? ` ${i.fleetState}` : ''
36
- console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst} release ${release}${fleet}`)
38
+ // A RETIRED deployment's retained resources still cost the org: say when it was retired and by whom.
39
+ const retired = i.retiredAt ? ` retired ${i.retiredAt}${i.retiredBy ? ` by ${i.retiredBy}` : ''}` : ''
40
+ console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst} release ${release}${fleet}${retired}`)
37
41
  }
38
42
  }
39
43
  return view
40
44
  }
41
45
 
42
- // Roll an existing deployment's modules to a new commit (the upgrade path; `deploy` only creates). --param changes
43
- // settings instead, through the settings route (`saaslayer settings set`), keeping the current commit. --manifest
46
+ // Roll an existing deployment's modules to a new release (the upgrade path; `deploy` only creates): --version, or
47
+ // --channel for what a channel points at now (--commit-sha until the control plane refuses it). --param changes
48
+ // settings instead, through the settings route (`saaslayer settings set`), keeping the current release. --manifest
44
49
  // applies a tested release manifest (commands/release-manifest.js).
45
50
  async function update(flags) {
46
51
  if (flags.manifest !== undefined) return require('./release-manifest').updateFromManifest(flags)
47
- const commitSha = flags['commit-sha'] || flags.commitSha
52
+ const retrying = flags.retry === true || flags.retry === 'true'
53
+ if (retrying) return retry(flags, Boolean(flags['commit-sha'] || flags.commitSha || flags.version !== undefined || flags.channel !== undefined || flags.param !== undefined))
54
+ const choice = releaseChoice(flags)
48
55
  const parameters = parseSetFlags(flags.param, '--param')
49
- if (!commitSha && !parameters) throw new Error('update requires --commit-sha <sha> (or --param <module>.<Setting>=<value> to change settings)')
50
- if (commitSha && parameters) {
51
- throw new Error('update moves a release (--commit-sha) or changes settings (--param), not both: run `saaslayer update --commit-sha <sha>`, then `saaslayer settings set --set <module>.<Setting>=<value>`')
56
+ if (!choice && !parameters) throw new Error('update requires --version <semver> or --channel <name> (saaslayer versions lists them), or --param <module>.<Setting>=<value> to change settings')
57
+ if (choice && parameters) {
58
+ throw new Error('update moves a release (--version, --channel or --commit-sha) or changes settings (--param), not both: run `saaslayer update --version <version>`, then `saaslayer settings set --set <module>.<Setting>=<value>`')
52
59
  }
53
60
  if (parameters) {
54
61
  checkParamModules(parameters, await fetchModuleCatalog(flags))
55
62
  return applySettings(parameters, flags)
56
63
  }
64
+ const resolved = await checkReleaseChoice(choice, flags)
57
65
  const d = await resolveDeployment(flags)
58
- console.log(`Updating ${d.project}/${d.env}/${d.region} (${d.deploymentId}) to ${commitSha}…`)
66
+ console.log(`Updating ${d.project}/${d.env}/${d.region} (${d.deploymentId}) to ${describeChoice(choice, resolved)}…`)
67
+ if (resolved && resolved.compat === 'breaking') console.log(` ${resolved.version} is a breaking release${resolved.notes ? `: ${resolved.notes}` : ''}`)
59
68
  // Protected envs (staging/prod) require --reason; --force passes the drift gate (audited with the reason).
60
- const attributes = { commitSha }
69
+ const attributes = { ...choice }
61
70
  if (flags.reason) attributes.reason = flags.reason
62
71
  if (flags.force === true || flags.force === 'true') attributes.force = true
63
72
  const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
@@ -66,6 +75,45 @@ async function update(flags) {
66
75
  return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
67
76
  }
68
77
 
78
+ /**
79
+ * Retry the deployment at its deployed release with its stored settings: the same managed source, nothing rewritten.
80
+ * It resumes any accepted sign-in method that is not ready (and anything else a same-release update does); with nothing
81
+ * to resume the control plane answers NOOP.
82
+ * @param {Record<string, any>} flags
83
+ * @param {boolean} changes a release (--version, --channel, --commit-sha) or --param was given too
84
+ */
85
+ async function retry(flags, changes) {
86
+ if (changes) throw new Error('--retry redeploys the deployed release: leave out --version, --channel, --commit-sha and --param')
87
+ const d = await resolveDeployment(flags)
88
+ if (!d.commitSha) throw new Error(`${d.deploymentId} has no deployed release to retry (status ${d.status || '—'}); deploy it first`)
89
+ if (!flags.reason && PROTECTED_ENVS.has(d.env)) throw new Error(`\`update --retry\` on ${d.env} (protected) requires --reason <text>`)
90
+ // Sign-in methods not ready, none of which the deployer says a retry resumes (retryable): none is sent.
91
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(d.deploymentId)}/settings`, undefined, flags)
92
+ const report = (doc && doc.data && doc.data.attributes && doc.data.attributes.loginMethods) || []
93
+ const notReady = report.flatMap((state) => state.methods.filter((m) => m.stage !== 'ready'))
94
+ if (notReady.length && !notReady.some((m) => m.retryable)) {
95
+ console.log('nothing to retry: a retry cannot fix what is pending')
96
+ for (const m of notReady) console.log(` ${m.loginMethod} ${m.role} (${m.reason || m.stage}): ${m.guidance}`)
97
+ return null
98
+ }
99
+ console.log(`Retrying ${d.project}/${d.env}/${d.region} (${d.deploymentId}) at its deployed release ${d.version || String(d.commitSha).slice(0, 8)} with its stored settings…`)
100
+ // No release field: the control plane keeps the deployment's own commit.
101
+ const attributes = { ...(flags.reason ? { reason: flags.reason } : {}) }
102
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
103
+ .catch((err) => {
104
+ const hint = signInRefusalHint(err, d.env)
105
+ if (hint) err.message += `\n${hint}`
106
+ throw err
107
+ })
108
+ const status = res && res.data && res.data.attributes && res.data.attributes.status
109
+ if (status === 'NOOP') {
110
+ console.log('nothing to retry: the deployment is at its release and every accepted sign-in method is ready')
111
+ return res
112
+ }
113
+ console.log(`✅ retry started for ${d.deploymentId}${status ? ` (${status})` : ''}`)
114
+ return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
115
+ }
116
+
69
117
  /**
70
118
  * Approve the migrations one run left awaiting approval (a protected env's destructive/contract migrations): the control
71
119
  * plane starts the run that applies them, recording you and the reason. `saaslayer update` prints the run id.
@@ -82,24 +130,101 @@ async function approveMigrations(flags) {
82
130
  return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
83
131
  }
84
132
 
133
+ // The next command for a destroy refusal that has one.
134
+ const DESTROY_NEXT_ACTIONS = {
135
+ PURGE_FOUNDATION_TOO_OLD: 'saaslayer foundation upgrade',
136
+ PROTECTED_TEARDOWN_FOUNDATION_TOO_OLD: 'saaslayer foundation upgrade',
137
+ }
138
+ const RETAINED_COST_NOTICE = "Retained resources remain your organization's responsibility and cost until purged: saaslayer destroy --purge-retained --reason TEXT"
139
+
140
+ /**
141
+ * A purge's report (ADR 0006 §5 purgeResult) as lines: the state and counts, then each residual (with when AWS finishes
142
+ * it), failed and outside-custody item.
143
+ * @param {{ state?: string, removed?: object[], residual?: Array<Record<string, unknown>>, failed?: Array<Record<string, unknown>>, outsideCustody?: Array<Record<string, unknown>> }} purgeResult
144
+ * @returns {string[]}
145
+ */
146
+ function formatPurgeResult(purgeResult) {
147
+ const list = (/** @type {unknown} */ v) => (Array.isArray(v) ? v : [])
148
+ const { removed, residual, failed, outsideCustody } = { removed: list(purgeResult.removed), residual: list(purgeResult.residual), failed: list(purgeResult.failed), outsideCustody: list(purgeResult.outsideCustody) }
149
+ const lines = [`purge ${purgeResult.state || 'unknown'}: ${removed.length} removed, ${residual.length} residual, ${failed.length} failed, ${outsideCustody.length} outside custody`]
150
+ for (const r of residual) lines.push(` residual ${r.kind} ${r.id}${r.expiresAt ? ` until ${r.expiresAt}` : ''}: ${r.reason}`)
151
+ for (const f of failed) lines.push(` failed ${f.kind} ${f.id}: ${f.reason}`)
152
+ for (const o of outsideCustody) lines.push(` outside custody ${o.kind} ${o.id}: ${o.reason}`)
153
+ if (purgeResult.state === 'pending') lines.push(' pending items are re-checked by the control plane; see saaslayer status')
154
+ return lines
155
+ }
156
+
157
+ /** Print a purgeResult when the response or its operation carries one. @param {unknown} purgeResult */
158
+ function printPurgeResult(purgeResult) {
159
+ if (purgeResult && typeof purgeResult === 'object') console.log(formatPurgeResult(/** @type {object} */ (purgeResult)).join('\n'))
160
+ }
161
+
162
+ /**
163
+ * `saaslayer destroy`: tear a deployment down with --data-custody delete|retain, or purge what a retain destroy kept
164
+ * (--purge-retained). A protected env (staging, prod) and every purge need --reason; the typed project name confirms.
165
+ * @param {Record<string, any>} flags
166
+ */
85
167
  async function destroy(flags) {
168
+ const purge = flags['purge-retained'] === true || flags['purge-retained'] === 'true'
86
169
  const dataCustody = flags['data-custody']
87
- if (dataCustody !== 'delete' && dataCustody !== 'retain') throw new Error('destroy requires --data-custody delete|retain')
88
- // Prod destroy is audited: the deployer requires an explicit reason. Default a sensible one when --reason is omitted.
89
- const reason = flags.reason || 'destroyed via saaslayer CLI'
170
+ if (purge && dataCustody !== undefined) throw new Error('--purge-retained purges what a retain destroy kept: it takes no --data-custody')
171
+ if (!purge && dataCustody !== 'delete' && dataCustody !== 'retain') throw new Error('destroy requires --data-custody delete|retain (or --purge-retained)')
172
+ const reason = typeof flags.reason === 'string' ? flags.reason.trim() : ''
173
+ if (purge && !reason) throw new Error('--purge-retained requires --reason <text>')
90
174
  const d = await resolveDeployment(flags)
91
- console.log(`⚠ This will DESTROY ${d.project}/${d.env}/${d.region} (${d.deploymentId}), data-custody=${dataCustody}.`)
175
+ if (PROTECTED_ENVS.has(d.env) && !reason) throw new Error(`destroy on ${d.env} (protected) requires --reason <text>`)
176
+ const target = `${d.project}/${d.env}/${d.region} (${d.deploymentId})`
177
+ if (purge) {
178
+ console.log(`⚠ This will PURGE the resources a retain destroy kept for ${target}.`)
179
+ console.log(' Purge permanently deletes the retained data; this cannot be undone.')
180
+ } else {
181
+ console.log(`⚠ This will DESTROY ${target}, data-custody=${dataCustody}.`)
182
+ console.log(dataCustody === 'retain' ? ` ${RETAINED_COST_NOTICE}` : " Delete custody permanently deletes the deployment's data; this cannot be undone.")
183
+ }
92
184
  const typed = flags.yes ? d.project : await ask(`Type the project name "${d.project}" to confirm: `)
93
185
  if (typed !== d.project) { console.log('Aborted (name did not match).'); return null }
94
- const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}?dataCustody=${dataCustody}&reason=${encodeURIComponent(reason)}`, undefined, flags)
95
- console.log(`✅ destroy started for ${d.deploymentId}`)
96
- return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
186
+ const query = new URLSearchParams(purge ? { purgeRetained: 'true' } : { dataCustody })
187
+ if (reason) query.set('reason', reason)
188
+ let res
189
+ try {
190
+ res = await jsonApiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}?${query}`, undefined, flags)
191
+ } catch (err) {
192
+ const code = err && err.body && Array.isArray(err.body.errors) && err.body.errors[0] ? err.body.errors[0].code : null
193
+ if (code && DESTROY_NEXT_ACTIONS[code]) err.message = `${err.message}\n next: ${DESTROY_NEXT_ACTIONS[code]}`
194
+ throw err
195
+ }
196
+ const attrs = (res && res.data && res.data.attributes) || {}
197
+ console.log(`✅ ${purge ? 'purge' : 'destroy'} started for ${d.deploymentId}${attrs.status ? ` (${attrs.status})` : ''}`)
198
+ if (attrs.warning) console.log(`⚠ ${attrs.warning}`)
199
+ printPurgeResult(attrs.purgeResult)
200
+ try {
201
+ const finished = await finishMutation({ response: res, deploymentId: d.deploymentId, flags })
202
+ if (finished && finished.operation) printPurgeResult(finished.operation.purgeResult)
203
+ return finished
204
+ } catch (err) {
205
+ if (err && err.operation) printPurgeResult(err.operation.purgeResult)
206
+ throw err
207
+ }
97
208
  }
98
209
 
99
210
  async function serviceAdd(service, flags) {
100
211
  if (!service) throw new Error('`service add` requires a service name')
212
+ let parameters
213
+ const input = mergePatches(typeof flags.settings === 'string' ? readSettingsFile(flags.settings) : undefined, parseSetFlags(flags.param, '--param'))
101
214
  const d = await resolveDeployment(flags)
102
- const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services`, { data: { type: 'service', attributes: { service } } }, flags, { headers: requestKeyHeaders() })
215
+ if (input && Object.keys(input).length) {
216
+ const catalog = await fetchModuleCatalog(flags)
217
+ // Catalog selection is by service type; pass the canonical instance reference unchanged to the server's identity kernel.
218
+ const selected = catalog.find(({ id }) => service === id || service.startsWith(`${id}@`))
219
+ if (!selected) throw new Error(`unknown service ${service}; saaslayer stacks lists the service types`)
220
+ if (Object.keys(input).some((id) => id !== selected.id)) throw new Error(`service add ${service} accepts settings for ${selected.id} only`)
221
+ const deployment = await apiCall('GET', `/api/deployments/${encodeURIComponent(d.deploymentId)}`, undefined, flags)
222
+ const revision = deployment.data?.attributes?.commitSha
223
+ if (!revision) throw new Error('service add settings require the published settings schema; the deployment reports no revision')
224
+ const schema = await fetchSchema(selected.id, revision, flags)
225
+ parameters = checkPatch(input, { [selected.id]: schema }, { op: 'create' }).patch[selected.id]
226
+ }
227
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services`, { data: { type: 'service', attributes: { service, ...(parameters ? { parameters } : {}) } } }, flags, { headers: requestKeyHeaders() })
103
228
  console.log(`✅ adding ${service} to ${d.deploymentId}`)
104
229
  return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
105
230
  }
@@ -125,4 +250,4 @@ async function serviceRemove(service, flags) {
125
250
  return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
126
251
  }
127
252
 
128
- module.exports = { status, update, approveMigrations, destroy, serviceAdd, serviceRemove }
253
+ module.exports = { status, update, approveMigrations, destroy, formatPurgeResult, serviceAdd, serviceRemove }
@@ -0,0 +1,259 @@
1
+ // `saaslayer login-domain status|provision|activate|deactivate|remove`: one user-service instance's branded login domain
2
+ // (GET|POST|DELETE /api/deployments/{id}/services/{ref}/login-domain); activate and deactivate are the E8 handoff.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { apiCall } = require('../api-client')
6
+ const { resolveDeployment } = require('../deployments')
7
+ const { finishMutation } = require('./operations')
8
+ const { PROTECTED_ENVS } = require('../settings')
9
+ const { chooseInstance, refOf } = require('../user-service-instance')
10
+ const { admitLoginDomainSwitch, loginDomainChecklist } = require('../login-domain')
11
+
12
+ const USAGE = 'usage: saaslayer login-domain <status|provision|activate|deactivate|remove> [managed|<host>] [--env E] [--service REF] … (see saaslayer --help)'
13
+ // States before the custom domain's alias exists: a lookup of the final CNAME then can be negatively cached.
14
+ const BEFORE_ALIAS = new Set(['requested', 'issued', 'provisioning'])
15
+ // ACM publishes a new cert's validation record a few seconds after the request: a first answer without it is re-read
16
+ // this often, this many times (~20 s), before saying it is not ready yet.
17
+ const VALIDATION_POLL_MS = 2000
18
+ const VALIDATION_POLLS = 10
19
+
20
+ /** @param {string|null|undefined} host */
21
+ const redirectUri = (host) => `https://${host}/oauth2/idpresponse`
22
+
23
+ /**
24
+ * Rollback limit: deactivate advertises the opaque host again, where Google sign-in needs its redirect URI registered.
25
+ * @param {string} opaqueHost
26
+ */
27
+ const deactivateWarning = (opaqueHost) => `note: deactivate advertises ${opaqueHost} again: Google sign-in there needs ${redirectUri(opaqueHost)} registered in the Google client; re-add it first if it was removed`
28
+ // Rollback limit: apps that kept the removed host's URL do not follow discovery to the next one.
29
+ const REMOVE_WARNING = 'note: apps configured with the removed login domain\'s URL (SAASLAYER_HOSTED_LOGIN_URL from saaslayer env export) stop reaching sign-in until they re-read discovery or are rebuilt'
30
+
31
+ /**
32
+ * The deployment, its chosen user-service instance and the instance's login-domain path.
33
+ * @param {Record<string, any>} flags
34
+ */
35
+ async function resolveInstance(flags) {
36
+ const deployment = await resolveDeployment(flags)
37
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}`, undefined, flags)
38
+ const detail = { deploymentId: deployment.deploymentId, ...doc.data.attributes }
39
+ const service = refOf(chooseInstance(detail, flags))
40
+ const loginDomainPath = `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/services/${encodeURIComponent(service)}/login-domain`
41
+ return { deployment, region: detail.region || deployment.region, service, loginDomainPath }
42
+ }
43
+
44
+ /** @param {{ name: string, type: string, value: string }} record */
45
+ const recordLine = (record) => `${record.name} ${record.type} ${record.value}`
46
+
47
+ /** The DNS records a custom login domain needs. @param {Record<string, any>|null|undefined} records */
48
+ function recordLines(records) {
49
+ if (!records) return []
50
+ return [
51
+ ...(records.validation ? [` validation: ${recordLine(records.validation)}`] : []),
52
+ ...(records.final ? [` final: ${recordLine(records.final)}`] : []),
53
+ ]
54
+ }
55
+
56
+ /**
57
+ * The redirect URIs to keep registered in each provider console: the active host's, then any other the instance serves.
58
+ * @param {Record<string, any>} status
59
+ * @returns {Array<{ uri: string, label: string }>}
60
+ */
61
+ function redirectUrisOf(status) {
62
+ const active = status.activeHost ? redirectUri(status.activeHost) : null
63
+ const pending = [...(status.host ? [redirectUri(status.host)] : []), ...(status.redirectUris || [])]
64
+ const opaque = status.opaqueHost ? [redirectUri(status.opaqueHost)] : []
65
+ const seen = new Set()
66
+ return [
67
+ ...(active ? [{ uri: active, label: 'active' }] : []),
68
+ ...pending.map((uri) => ({ uri, label: 'pending' })),
69
+ ...opaque.map((uri) => ({ uri, label: 'opaque' })),
70
+ ].filter(({ uri }) => !seen.has(uri) && seen.add(uri))
71
+ }
72
+
73
+ /** @param {Record<string, any>} status @param {{ service: string, deploymentId: string, region: string }} where */
74
+ function formatStatus(status, { service, deploymentId, region }) {
75
+ const lines = [`${service} login domain on deployment ${deploymentId} (${region})`]
76
+ lines.push(status.host ? ` ${status.kind} ${status.host}: ${status.state}` : ' no custom login domain: the opaque login domain is advertised')
77
+ if (status.failureReason) lines.push(` ${status.state}: ${status.failureReason}`)
78
+ lines.push(` active host: ${status.activeHost || '—'}`, ` opaque host: ${status.opaqueHost || '—'}`)
79
+ if (status.certStatus) lines.push(` certificate: ${status.certStatus}`)
80
+ if (typeof status.dnsPointsCorrectly === 'boolean') lines.push(` DNS points correctly: ${status.dnsPointsCorrectly ? 'yes' : 'no'}`)
81
+ if (status.kind === 'custom' && status.records) {
82
+ lines.push(' records to add at your DNS provider:', ...recordLines(status.records))
83
+ if (BEFORE_ALIAS.has(status.state)) lines.push(' note: a lookup of the final CNAME before its target exists can be cached as NXDOMAIN for up to 24 h')
84
+ }
85
+ const uris = redirectUrisOf(status)
86
+ if (uris.length) lines.push(' redirect URIs to keep registered in each provider console:', ...uris.map(({ uri, label }) => ` ${uri} (${label})`))
87
+ if (status.quota) lines.push(` quota: ${status.quota.used} of ${status.quota.cap} custom login domains used in this account and region`)
88
+ if (status.activeHost && status.opaqueHost && status.activeHost !== status.opaqueHost) lines.push(` ${deactivateWarning(status.opaqueHost)}`)
89
+ return lines
90
+ }
91
+
92
+ /** @param {string} path @param {Record<string, any>} flags */
93
+ async function readStatus(path, flags) {
94
+ const doc = await apiCall('GET', path, undefined, flags)
95
+ return doc.data.attributes
96
+ }
97
+
98
+ /**
99
+ * A refusal as `<code>: <title>`; with --json the refusal document is printed as is.
100
+ * @param {any} err @param {Record<string, any>} flags
101
+ */
102
+ function refusalOf(err, flags) {
103
+ const first = err && err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
104
+ if (!first) return err
105
+ if (flags.json) console.log(JSON.stringify({ errors: err.body.errors }, null, 2))
106
+ return Object.assign(new Error(`${first.code || err.status}: ${first.title || first.detail || 'request refused'}`), { status: err.status, body: err.body })
107
+ }
108
+
109
+ /** The written --reason, or undefined. @param {Record<string, any>} flags */
110
+ const reasonOf = (flags) => (typeof flags.reason === 'string' && flags.reason.trim() ? flags.reason.trim() : undefined)
111
+
112
+ /**
113
+ * Send one login-domain change (a POST carries an Idempotency-Key); the answer is the login-domain status with the
114
+ * operation the change started (null when none).
115
+ * @param {string} method @param {string} path @param {object} attributes @param {Record<string, any>} flags
116
+ */
117
+ async function send(method, path, attributes, flags) {
118
+ const headers = method === 'POST' ? { 'idempotency-key': `cli-${crypto.randomUUID()}` } : {}
119
+ try {
120
+ return await apiCall(method, path, { data: { type: 'login-domains', attributes } }, flags, { headers })
121
+ } catch (err) {
122
+ throw refusalOf(err, flags)
123
+ }
124
+ }
125
+
126
+ /** Whether a change answer started a run. @param {any} res */
127
+ const startedRun = (res) => typeof res.data.attributes.operationId === 'string' && res.data.attributes.operationId !== ''
128
+
129
+ /**
130
+ * Print a started run and wait on it.
131
+ * @param {any} res @param {string} label @param {{ service: string, deployment: { deploymentId: string } }} where @param {Record<string, any>} flags
132
+ */
133
+ async function followRun(res, label, { service, deployment }, flags) {
134
+ const answered = res.data.attributes
135
+ if (flags.json) console.log(JSON.stringify(answered, null, 2))
136
+ else console.log(`login domain ${label} on ${service} of ${deployment.deploymentId}: operation ${answered.operationId}`)
137
+ return finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
138
+ }
139
+
140
+ /** Whether a requested custom domain's answer still lacks ACM's validation record. @param {Record<string, any>} status */
141
+ const awaitingValidationRecord = (status) => status.state === 'requested' && !(status.records && status.records.validation)
142
+
143
+ /**
144
+ * The status once ACM has published the validation record: re-read every VALIDATION_POLL_MS, at most VALIDATION_POLLS
145
+ * times; the last status read when it never appears.
146
+ * @param {Record<string, any>} answered @param {string} path @param {Record<string, any>} flags
147
+ * @param {{ sleep: (ms: number) => Promise<void> }} deps
148
+ */
149
+ async function withValidationRecord(answered, path, flags, { sleep }) {
150
+ let status = answered
151
+ for (let poll = 0; poll < VALIDATION_POLLS && awaitingValidationRecord(status); poll += 1) {
152
+ await sleep(VALIDATION_POLL_MS)
153
+ status = await readStatus(path, flags)
154
+ }
155
+ return status
156
+ }
157
+
158
+ /**
159
+ * `provision managed|<host>`. @param {string|undefined} target @param {Record<string, any>} flags
160
+ * @param {{ sleep: (ms: number) => Promise<void> }} deps
161
+ */
162
+ async function provision(target, flags, deps) {
163
+ if (!target) throw new Error('login-domain provision needs managed or a host, e.g. saaslayer login-domain provision managed --env prod --reason "branded login host"')
164
+ const where = await resolveInstance(flags)
165
+ const reason = reasonOf(flags)
166
+ if (!reason && PROTECTED_ENVS.has(where.deployment.env)) throw new Error(`${where.deployment.env} is a protected environment: pass --reason <text>`)
167
+ const kind = target === 'managed' ? { kind: 'managed' } : { kind: 'custom', host: target }
168
+ const res = await send('POST', where.loginDomainPath, { ...kind, ...(reason ? { reason } : {}) }, flags)
169
+ if (startedRun(res)) return followRun(res, `provision (${target})`, where, flags)
170
+ const answered = await withValidationRecord(res.data.attributes, where.loginDomainPath, flags, deps)
171
+ if (flags.json) console.log(JSON.stringify(answered, null, 2))
172
+ else for (const line of provisionOutcome(answered, target, where.service)) console.log(line)
173
+ return res
174
+ }
175
+
176
+ /**
177
+ * What a provision answered without a run means, and the next step.
178
+ * @param {Record<string, any>} answered the login-domain status @param {string} target @param {string} service
179
+ */
180
+ function provisionOutcome(answered, target, service) {
181
+ const host = answered.host || target
182
+ if (answered.state === 'requested') {
183
+ return [
184
+ `certificate for ${host}: ${answered.certStatus || 'PENDING_VALIDATION'}; add these records:`, ...recordLines(answered.records),
185
+ ...(awaitingValidationRecord(answered) ? [' validation record not ready yet; run saaslayer login-domain status'] : []),
186
+ `then run saaslayer login-domain provision ${target} again once the certificate is ISSUED (saaslayer login-domain status shows it)`,
187
+ ]
188
+ }
189
+ if (answered.state === 'issued') {
190
+ const final = answered.records && answered.records.final
191
+ return [`certificate for ${host} is ISSUED; point ${final ? recordLine(final) : `${host} at its indirection host`}, then run saaslayer login-domain provision ${target} again`]
192
+ }
193
+ if (answered.state === 'unavailable' || answered.state === 'failed') return [`login domain ${host} is ${answered.state}: ${answered.failureReason || 'no reason given'}`]
194
+ return [`login domain ${host} is already ${answered.state} on ${service}`]
195
+ }
196
+
197
+ /**
198
+ * `activate` (advertise the custom host) or `deactivate` (advertise the opaque host again): the E8 handoff, checked
199
+ * here against the current host before anything is sent, then the completion checklist once the run is accepted.
200
+ * @param {'activate'|'deactivate'} sub @param {Record<string, any>} flags
201
+ */
202
+ async function switchHost(sub, flags) {
203
+ const where = await resolveInstance(flags)
204
+ const status = await readStatus(where.loginDomainPath, flags)
205
+ const toHost = sub === 'activate' ? status.host : status.opaqueHost
206
+ if (status.activeHost === toHost) {
207
+ console.log(sub === 'activate' ? `${toHost} is already the active login domain of ${where.service}` : `${where.service} already advertises its opaque login domain ${toHost}`)
208
+ return null
209
+ }
210
+ if (sub === 'activate' && !status.host) throw new Error(`${where.service} has no custom login domain to activate: run saaslayer login-domain provision managed|<host> first`)
211
+ const settingsDoc = await apiCall('GET', `/api/deployments/${encodeURIComponent(where.deployment.deploymentId)}/settings`, undefined, flags)
212
+ const { domainHandoff, handoff } = admitLoginDomainSwitch({ service: where.service, fromHost: status.activeHost, toHost, settings: settingsDoc.data.attributes, flags })
213
+ if (sub === 'deactivate' && !flags.json) console.log(deactivateWarning(toHost))
214
+ const res = await send('POST', `${where.loginDomainPath}/${sub}`, { reason: domainHandoff.reason, domainHandoff }, flags)
215
+ if (!startedRun(res)) {
216
+ if (flags.json) console.log(JSON.stringify(res.data.attributes, null, 2))
217
+ else console.log(`${res.data.attributes.activeHost} is already the active login domain of ${where.service}`)
218
+ return res
219
+ }
220
+ const result = await followRun(res, `${sub} (${toHost})`, where, flags)
221
+ if (!flags.json) {
222
+ console.log('Login domain handoff: the confirmation acknowledges what breaks; finish each step:')
223
+ for (const line of loginDomainChecklist([handoff])) console.log(line)
224
+ }
225
+ return result
226
+ }
227
+
228
+ /** `remove`: delete the custom domain, its alias and (custom) its certificate. @param {Record<string, any>} flags */
229
+ async function remove(flags) {
230
+ const where = await resolveInstance(flags)
231
+ const reason = reasonOf(flags)
232
+ if (!reason && PROTECTED_ENVS.has(where.deployment.env)) throw new Error(`${where.deployment.env} is a protected environment: pass --reason <text>`)
233
+ if (!flags.json) console.log(REMOVE_WARNING)
234
+ const res = await send('DELETE', where.loginDomainPath, reason ? { reason } : {}, flags)
235
+ return followRun(res, 'remove', where, flags)
236
+ }
237
+
238
+ /**
239
+ * @param {string|undefined} sub status | provision | activate | deactivate | remove
240
+ * @param {string|undefined} target provision's managed | <host>
241
+ * @param {Record<string, any>} flags
242
+ * @param {{ sleep?: (ms: number) => Promise<void> }} [deps]
243
+ */
244
+ async function loginDomainCommand(sub, target, flags, deps = {}) {
245
+ const sleep = deps.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
246
+ if (sub === 'status') {
247
+ const where = await resolveInstance(flags)
248
+ const status = await readStatus(where.loginDomainPath, flags)
249
+ const shown = { deploymentId: where.deployment.deploymentId, service: where.service, ...status }
250
+ console.log(flags.json ? JSON.stringify(shown, null, 2) : formatStatus(status, { service: where.service, deploymentId: where.deployment.deploymentId, region: where.region }).join('\n'))
251
+ return status
252
+ }
253
+ if (sub === 'provision') return provision(target, flags, { sleep })
254
+ if (sub === 'activate' || sub === 'deactivate') return switchHost(sub, flags)
255
+ if (sub === 'remove') return remove(flags)
256
+ throw new Error(USAGE)
257
+ }
258
+
259
+ module.exports = { loginDomainCommand, redirectUrisOf }
@@ -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 }