saaslayer 0.0.7 → 0.2.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 (48) hide show
  1. package/README.md +150 -13
  2. package/bin/saaslayer.js +318 -66
  3. package/package.json +4 -3
  4. package/src/api-client.js +48 -28
  5. package/src/aws-sigv4.js +1 -1
  6. package/src/commands/access-admins.js +73 -0
  7. package/src/commands/accounts.js +32 -3
  8. package/src/commands/activity.js +33 -0
  9. package/src/commands/aws.js +55 -6
  10. package/src/commands/catalog.js +30 -29
  11. package/src/commands/context.js +64 -0
  12. package/src/commands/deploy.js +79 -10
  13. package/src/commands/first-admin.js +42 -0
  14. package/src/commands/foundation.js +456 -0
  15. package/src/commands/integration-credentials.js +66 -0
  16. package/src/commands/lifecycle.js +77 -40
  17. package/src/commands/login.js +200 -26
  18. package/src/commands/machine-trust.js +96 -0
  19. package/src/commands/operations.js +140 -0
  20. package/src/commands/orgs.js +29 -4
  21. package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
  22. package/src/commands/release-manifest.js +138 -0
  23. package/src/commands/service-principals.js +81 -0
  24. package/src/commands/settings.js +140 -0
  25. package/src/commands/stacks.js +12 -7
  26. package/src/commands/users-management.js +401 -0
  27. package/src/commands/users.js +192 -4
  28. package/src/config.js +20 -7
  29. package/src/credentials.js +221 -34
  30. package/src/deployment-api-auth.js +61 -0
  31. package/src/deployment-auth.js +38 -0
  32. package/src/deployments.js +12 -13
  33. package/src/discovery.js +66 -0
  34. package/src/env-compare.js +143 -0
  35. package/src/iam-session.js +4 -30
  36. package/src/module-catalog.js +66 -0
  37. package/src/permissions-request.js +43 -0
  38. package/src/release-manifest.js +334 -0
  39. package/src/scope.js +114 -0
  40. package/src/settings.js +272 -0
  41. package/src/users-api.js +165 -0
  42. package/src/users-import/import.js +10 -10
  43. package/templates/saaslayer-foundation-region.yml +37 -1
  44. package/templates/saaslayer-foundation.yml +63 -10
  45. package/src/commands/iam-principals.js +0 -53
  46. package/src/rbac-auth.js +0 -25
  47. package/vendor/ids/index.d.ts +0 -21
  48. package/vendor/ids/index.js +0 -237
@@ -0,0 +1,66 @@
1
+ // `saaslayer credentials status|revoke --deployment <id> --service <ref>`: an org owner reads a user-service instance's
2
+ // integration credentials (key ids, state, age; never a value) or revokes one key (reason required) through the console.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { apiCall } = require('../api-client')
6
+
7
+ const KINDS = ['email-authoring', 'config']
8
+
9
+ /** @param {object} flags @param {string} name */
10
+ const required = (flags, name) => {
11
+ const value = flags[name]
12
+ if (typeof value !== 'string' || !value.trim()) throw new Error(`--${name} is required`)
13
+ return value.trim()
14
+ }
15
+
16
+ /** @param {object} flags */
17
+ function basePath(flags) {
18
+ return `/api/deployments/${encodeURIComponent(required(flags, 'deployment'))}/services/${encodeURIComponent(required(flags, 'service'))}/credentials`
19
+ }
20
+
21
+ /**
22
+ * One line per key and the pending operation, from a status document.
23
+ * @param {Record<string, any>} attrs
24
+ * @returns {string[]}
25
+ */
26
+ function formatStatus(attrs) {
27
+ const lines = []
28
+ for (const [kind, keys] of Object.entries(attrs.kinds || {})) {
29
+ for (const k of keys) lines.push(`${kind} ${k.keyId} ${k.state} age ${k.ageDays}d ${k.accepted ? 'accepted' : 'pending acceptance'}`)
30
+ }
31
+ const op = attrs.operation
32
+ if (op && op.operationId) lines.push(`operation ${op.operationId} ${op.phase} ${op.status}${op.detail ? ` — ${op.detail}` : ''}`)
33
+ return lines.length ? lines : ['no integration credentials']
34
+ }
35
+
36
+ /**
37
+ * Print the instance's integration credentials (or the document with --json) and return its attributes.
38
+ * @param {object} flags
39
+ */
40
+ async function credentialsStatus(flags) {
41
+ const doc = await apiCall('GET', basePath(flags), undefined, flags)
42
+ const attrs = (doc && doc.data && doc.data.attributes) || {}
43
+ console.log(flags.json ? JSON.stringify(attrs, null, 2) : formatStatus(attrs).join('\n'))
44
+ return attrs
45
+ }
46
+
47
+ /**
48
+ * Revoke one key now (no delay). The answer is the pending operation: the old key stops working once every verifier
49
+ * has the replacement; the console sends the replacement only then.
50
+ * @param {object} flags
51
+ */
52
+ async function credentialsRevoke(flags) {
53
+ const kind = required(flags, 'kind')
54
+ if (!KINDS.includes(kind)) throw new Error(`--kind must be one of ${KINDS.join(', ')}`)
55
+ const keyId = required(flags, 'key-id')
56
+ const reason = required(flags, 'reason')
57
+ const path = `${basePath(flags)}/revoke`
58
+ const doc = await apiCall('POST', path, { data: { type: 'credential-revocations', attributes: { kind, keyId, reason } } }, flags, { headers: { 'Idempotency-Key': `cli-${crypto.randomUUID()}` } })
59
+ const attrs = (doc && doc.data && doc.data.attributes) || {}
60
+ console.log(flags.json
61
+ ? JSON.stringify(attrs, null, 2)
62
+ : `revoke of ${keyId}: operation ${attrs.operationId} ${attrs.status}${attrs.replacementKeyId ? ` (replacement ${attrs.replacementKeyId})` : ''}; check with \`saaslayer credentials status\``)
63
+ return attrs
64
+ }
65
+
66
+ module.exports = { credentialsStatus, credentialsRevoke, formatStatus }
@@ -1,59 +1,85 @@
1
1
  // `saaslayer status | update | destroy | service add|remove` (swf2.8) — lifecycle over a deployed project.
2
- // Each resolves the deployment id from (project, env, region) then calls the guarded BFF route. destroy +
3
- // service-remove (delete custody) are guarded: destroy needs a typed project-name confirmation.
2
+ // Each resolves the deployment id from (project, env, region) then calls the guarded BFF route and, unless --no-wait,
3
+ // waits for the resulting operation. destroy + service-remove (delete custody) are guarded: destroy needs a typed
4
+ // project-name confirmation; a protected-env service removal needs --reason and the typed service name.
4
5
  'use strict'
5
6
  const { apiCall } = require('../api-client')
6
- const { activeProject, resolveDeployment } = require('../deployments')
7
+ const { resolveDeployment } = require('../deployments')
8
+ const { resolveScope, printScope, deployedProjectsHint } = require('../scope')
7
9
  const { ask } = require('../prompt')
10
+ const { finishMutation, requestKeyHeaders } = require('./operations')
11
+ const { fetchModuleCatalog, checkParamModules } = require('../module-catalog')
12
+ const { PROTECTED_ENVS, parseSetFlags } = require('../settings')
13
+ const { applySettings } = require('./settings')
8
14
 
9
15
  async function status(flags) {
10
- const project = activeProject(flags)
16
+ const scope = resolveScope(flags, { env: 'all' })
17
+ printScope(scope, flags)
18
+ const project = scope.project.value
11
19
  const view = await apiCall('GET', `/api/projects/${encodeURIComponent(project)}/deployments`, undefined, flags)
12
- console.log(`Project ${project}: ${view.instanceCount || 0} deployment(s)`)
13
- for (const g of view.environments || []) {
20
+ // --env narrows the listing to one deploy env; without it every live env is shown.
21
+ const groups = (view.environments || []).filter((g) => scope.env.value === 'all' || g.environment === scope.env.value)
22
+ const count = groups.reduce((n, g) => n + (g.instances || []).length, 0)
23
+ console.log(`Project ${project} (${scope.project.kind}): ${count} deployment(s)`)
24
+ if (!count) {
25
+ console.log(`no deployments for project ${project} (${scope.project.kind}) in org=${scope.org.value || '—'} env=${scope.env.value}`)
26
+ for (const line of await deployedProjectsHint(scope, flags)) console.log(line)
27
+ return view
28
+ }
29
+ for (const g of groups) {
14
30
  for (const i of g.instances || []) {
15
31
  const inst = i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''
16
- console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst}`)
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) : '—'
35
+ const fleet = i.fleetState && i.fleetState !== 'ACTIVE' ? ` ${i.fleetState}` : ''
36
+ console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst} release ${release}${fleet}`)
17
37
  }
18
38
  }
19
39
  return view
20
40
  }
21
41
 
22
- /**
23
- * `--param <service>.<Param>=<value>` flags (repeatable) as service-keyed parameters. The value may contain '=' or ','.
24
- * @param {unknown} raw
25
- * @returns {Record<string, Record<string, string>>|undefined}
26
- */
27
- function parseParams(raw) {
28
- if (raw === undefined) return undefined
29
- const parameters = {}
30
- for (const entry of Array.isArray(raw) ? raw : [raw]) {
31
- const m = typeof entry === 'string' ? /^([^.=]+)\.([^=]+)=(.*)$/s.exec(entry) : null
32
- if (!m) throw new Error('--param expects <service>.<Param>=<value>, e.g. --param user-service.AllowedAppOrigins=https://app.example.com')
33
- const [, service, name, value] = m
34
- parameters[service] = { ...(parameters[service] || {}), [name]: value }
35
- }
36
- return parameters
37
- }
38
-
39
- // Roll an existing deployment's modules to a new commit (the upgrade path; `deploy` only creates), and/or change its
40
- // update-safe settings with --param (a settings-only change keeps the current commit).
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
44
+ // applies a tested release manifest (commands/release-manifest.js).
41
45
  async function update(flags) {
46
+ if (flags.manifest !== undefined) return require('./release-manifest').updateFromManifest(flags)
42
47
  const commitSha = flags['commit-sha'] || flags.commitSha
43
- const parameters = parseParams(flags.param)
44
- if (!commitSha && !parameters) throw new Error('update requires --commit-sha <sha> (or --param <service>.<Param>=<value> to change settings)')
48
+ 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>`')
52
+ }
53
+ if (parameters) {
54
+ checkParamModules(parameters, await fetchModuleCatalog(flags))
55
+ return applySettings(parameters, flags)
56
+ }
45
57
  const d = await resolveDeployment(flags)
46
- console.log(`Updating ${d.project}/${d.env}/${d.region} (${d.deploymentId})${commitSha ? ` to ${commitSha}` : ''}${parameters ? ' with new settings' : ''}…`)
58
+ console.log(`Updating ${d.project}/${d.env}/${d.region} (${d.deploymentId}) to ${commitSha}…`)
47
59
  // Protected envs (staging/prod) require --reason; --force passes the drift gate (audited with the reason).
48
- const attributes = {}
49
- if (commitSha) attributes.commitSha = commitSha
50
- if (parameters) attributes.parameters = parameters
60
+ const attributes = { commitSha }
51
61
  if (flags.reason) attributes.reason = flags.reason
52
62
  if (flags.force === true || flags.force === 'true') attributes.force = true
53
- const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags)
63
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
54
64
  const status = res && res.data && res.data.attributes && res.data.attributes.status
55
65
  console.log(`✅ update started for ${d.deploymentId}${status ? ` (${status})` : ''}`)
56
- return res
66
+ return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
67
+ }
68
+
69
+ /**
70
+ * Approve the migrations one run left awaiting approval (a protected env's destructive/contract migrations): the control
71
+ * plane starts the run that applies them, recording you and the reason. `saaslayer update` prints the run id.
72
+ * @param {Record<string, any>} flags --run <runId>, --reason <text>, plus the usual scope flags
73
+ */
74
+ async function approveMigrations(flags) {
75
+ const runId = typeof flags.run === 'string' ? flags.run.trim() : ''
76
+ if (!runId) throw new Error('migrations approve requires --run <runId> (the update run that left migrations awaiting approval)')
77
+ const reason = typeof flags.reason === 'string' ? flags.reason.trim() : ''
78
+ if (!reason) throw new Error('migrations approve requires --reason <text> (recorded with the approval)')
79
+ const d = await resolveDeployment(flags)
80
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/migrations/approvals`, { data: { type: 'migration-approvals', attributes: { runId, reason } } }, flags, { headers: requestKeyHeaders() })
81
+ console.log(`✅ approved the migrations ${runId} left awaiting approval on ${d.deploymentId}`)
82
+ return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
57
83
  }
58
84
 
59
85
  async function destroy(flags) {
@@ -67,15 +93,15 @@ async function destroy(flags) {
67
93
  if (typed !== d.project) { console.log('Aborted (name did not match).'); return null }
68
94
  const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}?dataCustody=${dataCustody}&reason=${encodeURIComponent(reason)}`, undefined, flags)
69
95
  console.log(`✅ destroy started for ${d.deploymentId}`)
70
- return res
96
+ return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
71
97
  }
72
98
 
73
99
  async function serviceAdd(service, flags) {
74
100
  if (!service) throw new Error('`service add` requires a service name')
75
101
  const d = await resolveDeployment(flags)
76
- const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services`, { data: { type: 'service', attributes: { service } } }, flags)
102
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services`, { data: { type: 'service', attributes: { service } } }, flags, { headers: requestKeyHeaders() })
77
103
  console.log(`✅ adding ${service} to ${d.deploymentId}`)
78
- return res
104
+ return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
79
105
  }
80
106
 
81
107
  async function serviceRemove(service, flags) {
@@ -83,9 +109,20 @@ async function serviceRemove(service, flags) {
83
109
  const dataCustody = flags['data-custody']
84
110
  if (dataCustody !== 'delete' && dataCustody !== 'retain') throw new Error('`service remove` requires --data-custody delete|retain')
85
111
  const d = await resolveDeployment(flags)
86
- const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services/${encodeURIComponent(service)}?dataCustody=${dataCustody}`, undefined, flags)
112
+ // A protected env (staging, prod) removal is audited and confirmed: --reason, then the typed service name (--yes supplies it).
113
+ const isProtected = PROTECTED_ENVS.has(d.env)
114
+ if (isProtected && !flags.reason) throw new Error(`\`service remove\` on ${d.env} (protected) requires --reason <text>`)
115
+ const query = new URLSearchParams({ dataCustody })
116
+ if (flags.reason) query.set('reason', flags.reason)
117
+ if (isProtected) {
118
+ console.log(`⚠ This will REMOVE ${service} from ${d.project}/${d.env}/${d.region} (${d.deploymentId}), data-custody=${dataCustody}.`)
119
+ const typed = flags.yes ? service : await ask(`Type the service name "${service}" to confirm: `)
120
+ if (typed !== service) { console.log('Aborted (name did not match).'); return null }
121
+ query.set('confirmation', typed)
122
+ }
123
+ const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services/${encodeURIComponent(service)}?${query}`, undefined, flags, { headers: requestKeyHeaders() })
87
124
  console.log(`✅ removing ${service} from ${d.deploymentId} (data-custody=${dataCustody})`)
88
- return res
125
+ return finishMutation({ response: res, deploymentId: d.deploymentId, flags })
89
126
  }
90
127
 
91
- module.exports = { status, update, destroy, serviceAdd, serviceRemove }
128
+ module.exports = { status, update, approveMigrations, destroy, serviceAdd, serviceRemove }
@@ -1,46 +1,163 @@
1
- // `saaslayer login|logout|whoami` — authenticate to the global SaaSLayer user-service via Cognito SRP
2
- // (headless, D9) and cache tokens locally. Passwordless/FIDO2 opt-in opens a browser (fast-follow).
1
+ // `saaslayer login|logout|whoami` — authenticate via Cognito SRP (headless, D9) to the SaaSLayer control plane or, with
2
+ // --deployment, to a deployment's user-service (discovered from its public outputs), caching each login separately.
3
3
  'use strict'
4
4
  const readline = require('readline')
5
5
  const creds = require('../credentials')
6
- const { resolvePoolConfig, decodeJwt } = require('../config')
6
+ const { resolvePoolConfig, decodeJwt, controlPlaneUrl } = require('../config')
7
+ const { discoverDeployment, discoverFromFlags } = require('../discovery')
7
8
 
8
9
  // Prompt for a value; hidden masks input (passwords). Only used when no flag/env supplies it.
9
- function prompt(question, { hidden = false } = {}) {
10
+ function prompt(question, { hidden = false, input = process.stdin, output = process.stdout } = {}) {
10
11
  return new Promise((resolve) => {
11
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true })
12
+ const rl = readline.createInterface({ input, output, terminal: true })
12
13
  if (hidden) {
13
14
  // Suppress readline's own keystroke echo so only our mask shows (not char+mask interleaved).
14
15
  rl._writeToOutput = () => {}
15
- process.stdout.write(question)
16
16
  const onData = (char) => {
17
17
  char = String(char)
18
- if (char === '\u007f' || char === '\b') { process.stdout.write('\b \b'); return } // backspace
19
- if (['\n', '\r', ''].includes(char)) return
20
- process.stdout.write('*')
18
+ if (char === '\u007f' || char === '\b') { output.write('\b \b'); return } // backspace
19
+ if (['\n', '\r', ''].includes(char)) return
20
+ output.write('*')
21
21
  }
22
- process.stdin.on('data', onData)
23
- rl.question('', (answer) => { process.stdin.removeListener('data', onData); rl.close(); process.stdout.write('\n'); resolve(answer) })
22
+ input.on('data', onData)
23
+ rl.question('', (answer) => { input.removeListener('data', onData); rl.close(); output.write('\n'); resolve(answer) })
24
+ // Written after question(''): readline's line redraw clears the row, which erased a question written first.
25
+ output.write(question)
24
26
  } else {
25
27
  rl.question(question, (answer) => { rl.close(); resolve(answer) })
26
28
  }
27
29
  })
28
30
  }
29
31
 
30
- async function login(flags = {}) {
31
- const { srpLogin } = require('@davidwells/cogneato')
32
- const pool = await resolvePoolConfig(flags)
33
- const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
34
- const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Password: ', { hidden: true }))
32
+ /**
33
+ * @typedef {{ idToken: string, accessToken?: string, refreshToken?: string, expiresIn?: number }} LoginTokens
34
+ * @typedef {{ region: string, userPoolId: string, clientId: string }} PoolCoordinates
35
+ */
35
36
 
36
- const step = await srpLogin({ region: pool.region, userPoolId: pool.userPoolId, clientId: pool.clientId, username: email, password }).next()
37
- const value = step.value || {}
37
+ /**
38
+ * The tokens of a finished SRP step. A step the CLI cannot answer is refused with its name.
39
+ * @param {{ code?: string, error?: any, response?: { tokens: LoginTokens } }} value
40
+ * @returns {LoginTokens}
41
+ */
42
+ function tokensFromStep(value) {
38
43
  if (value.code === 'ERROR') throw new Error(`login failed: ${(value.error && (value.error.message || value.error)) || 'unknown error'}`)
39
- if (value.code !== 'TOKENS') {
40
- throw new Error(`login requires the '${value.code}' step (passwordless/MFA browser flow not yet wired); use SRP with a password`)
44
+ if (value.code !== 'TOKENS' || !value.response) {
45
+ throw new Error(`login requires the '${value.code}' step, which the CLI cannot answer; complete it in the hosted login page`)
46
+ }
47
+ return value.response.tokens
48
+ }
49
+
50
+ /** SRP challenge steps the CLI answers. */
51
+ const CHALLENGES = ['NEW_PASSWORD_REQUIRED', 'SOFTWARE_MFA_REQUIRED', 'SMS_MFA_REQUIRED']
52
+ const MAX_MFA_ATTEMPTS = 3
53
+
54
+ /**
55
+ * @typedef {{ isTTY: boolean, readStdin: () => Promise<string>, prompt: (question: string, opts?: { hidden?: boolean }) => Promise<string> }} LoginIo
56
+ * @typedef {{ code: string, hint?: string, error?: unknown }} ChallengeStep
57
+ */
58
+
59
+ /** @returns {Promise<string>} all of stdin */
60
+ async function readStdin() {
61
+ const chunks = []
62
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk))
63
+ return Buffer.concat(chunks).toString('utf8')
64
+ }
65
+
66
+ /** @type {LoginIo} */
67
+ const terminalIo = { get isTTY() { return Boolean(process.stdin.isTTY) }, readStdin, prompt }
68
+
69
+ /**
70
+ * The new password for NEW_PASSWORD_REQUIRED: piped on stdin with --new-password-stdin, else typed twice (hidden).
71
+ * @param {Record<string, any>} flags
72
+ * @param {LoginIo} io
73
+ * @returns {Promise<string>}
74
+ */
75
+ async function readNewPassword(flags, io) {
76
+ if (flags['new-password-stdin']) {
77
+ const piped = (await io.readStdin()).replace(/\r?\n$/, '')
78
+ if (!piped) throw new Error('new password read from stdin is empty')
79
+ return piped
80
+ }
81
+ if (!io.isTTY) throw new Error('this account requires a new password: pipe it with --new-password-stdin, or run login in a terminal')
82
+ const chosen = await io.prompt('New password: ', { hidden: true })
83
+ if (!chosen) throw new Error('new password is empty')
84
+ const confirmed = await io.prompt('Confirm new password: ', { hidden: true })
85
+ if (chosen !== confirmed) throw new Error('new passwords do not match')
86
+ return chosen
87
+ }
88
+
89
+ /**
90
+ * Answers the SRP challenges of one login from flags or the terminal. A code from --mfa-code is used once; when it
91
+ * is rejected the login fails. Typed codes are re-prompted up to MAX_MFA_ATTEMPTS. Answers are never printed.
92
+ * @param {Record<string, any>} flags --new-password-stdin, --mfa-code
93
+ * @param {LoginIo} io
94
+ * @returns {(step: ChallengeStep) => Promise<string>}
95
+ */
96
+ function challengeAnswerer(flags, io) {
97
+ let mfaAttempts = 0
98
+ let mfaFromFlag = false
99
+ return async (step) => {
100
+ if (step.code === 'NEW_PASSWORD_REQUIRED') return readNewPassword(flags, io)
101
+ const rejected = Boolean(step.error)
102
+ if (rejected && mfaFromFlag) throw new Error('MFA code was rejected')
103
+ if (rejected && mfaAttempts >= MAX_MFA_ATTEMPTS) throw new Error(`MFA code was rejected ${MAX_MFA_ATTEMPTS} times`)
104
+ if (flags['mfa-code'] !== undefined && !rejected) {
105
+ const code = flags['mfa-code']
106
+ if (typeof code !== 'string' || !/^\d{6}$/.test(code)) throw new Error('--mfa-code must be 6 digits')
107
+ mfaFromFlag = true
108
+ mfaAttempts++
109
+ return code
110
+ }
111
+ if (!io.isTTY) throw new Error('this account requires an MFA code: pass --mfa-code <6 digits>, or run login in a terminal')
112
+ const source = step.code === 'SMS_MFA_REQUIRED' ? `SMS code sent to ${step.hint || 'your phone'}` : 'MFA code from your authenticator app'
113
+ mfaAttempts++
114
+ return io.prompt(`${rejected ? 'Incorrect code. ' : ''}${source}: `, { hidden: true })
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Sign in to one Cognito pool client with SRP, answering NEW_PASSWORD_REQUIRED and MFA challenges from flags or the
120
+ * terminal. Both login authorities go through here.
121
+ * @param {PoolCoordinates} pool
122
+ * @param {{ email: string, password: string }} credentials
123
+ * @param {{ flags?: Record<string, any>, io?: LoginIo, srpLogin?: Function }} [opts]
124
+ * @returns {Promise<LoginTokens>}
125
+ */
126
+ async function authenticate(pool, { email, password }, { flags = {}, io = terminalIo, srpLogin } = {}) {
127
+ const run = srpLogin || require('@davidwells/cogneato').srpLogin
128
+ const steps = run({ region: pool.region, userPoolId: pool.userPoolId, clientId: pool.clientId, username: email, password })
129
+ const answer = challengeAnswerer(flags, io)
130
+ try {
131
+ let step = await steps.next()
132
+ while (!step.done && step.value && CHALLENGES.includes(step.value.code)) {
133
+ step = await steps.next(await answer(step.value))
134
+ }
135
+ return tokensFromStep(step.value || {})
136
+ } finally {
137
+ await steps.return(undefined)
41
138
  }
139
+ }
42
140
 
43
- const tokens = value.response.tokens
141
+ /**
142
+ * Email + password from flags, env or an interactive prompt.
143
+ * @param {Record<string, any>} flags
144
+ * @returns {Promise<{ email: string, password: string }>}
145
+ */
146
+ async function readCredentials(flags) {
147
+ const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
148
+ const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Password: ', { hidden: true }))
149
+ return { email, password }
150
+ }
151
+
152
+ /**
153
+ * Log in to the SaaSLayer control plane and make that account current. Deployment logins are not touched.
154
+ * @param {Record<string, any>} flags
155
+ * @param {{ authenticate?: typeof authenticate, srpLogin?: Function, io?: LoginIo }} [deps]
156
+ */
157
+ async function login(flags = {}, deps = {}) {
158
+ const pool = await resolvePoolConfig(flags)
159
+ const { email, password } = await readCredentials(flags)
160
+ const tokens = await (deps.authenticate || authenticate)(pool, { email, password }, { flags, io: deps.io, srpLogin: deps.srpLogin })
44
161
  const claims = decodeJwt(tokens.idToken)
45
162
  const userId = claims.sub
46
163
  const expiresAt = Math.floor(Date.now() / 1000) + (Number(tokens.expiresIn) || 3600)
@@ -48,6 +165,9 @@ async function login(flags = {}) {
48
165
  userId,
49
166
  email: claims.email || email,
50
167
  env: flags.env || 'prod',
168
+ issuer: claims.iss,
169
+ clientId: pool.clientId,
170
+ region: pool.region,
51
171
  idToken: tokens.idToken,
52
172
  accessToken: tokens.accessToken,
53
173
  refreshToken: tokens.refreshToken,
@@ -56,13 +176,55 @@ async function login(flags = {}) {
56
176
  return { userId, email: claims.email || email }
57
177
  }
58
178
 
179
+ /**
180
+ * `saaslayer login --deployment <dep_id|env>`: log in to a deployment's user-service (option B access admin).
181
+ * The pool, client and API bases come from the deployment's public discovery document; an environment name is first
182
+ * resolved to the project's deployment. The token must come from the discovered issuer and one of its app clients.
183
+ * The login is stored as its own profile and made the current deployment login; the control-plane login is kept.
184
+ * @param {Record<string, any>} flags --deployment, --user-service-instance, --region, --project, --config-url, --email, --password,
185
+ * --new-password-stdin, --mfa-code
186
+ * @param {{ authenticate?: typeof authenticate, discover?: typeof discoverDeployment, srpLogin?: Function, io?: LoginIo }} [deps]
187
+ */
188
+ async function loginDeployment(flags, deps = {}) {
189
+ const selector = flags.deployment
190
+ if (!selector || typeof selector !== 'string') throw new Error('login --deployment requires a deployment id (dep_…) or an environment name')
191
+ const { doc, deploymentId, environment, project } = await discoverFromFlags({ ...flags, 'discovery-url': undefined }, { discover: deps.discover })
192
+ const instance = flags['user-service-instance'] || null
193
+ const pool = { region: doc.region, userPoolId: doc.userPoolId, clientId: doc.clientId }
194
+ const { email, password } = await readCredentials(flags)
195
+ const tokens = await (deps.authenticate || authenticate)(pool, { email, password }, { flags, io: deps.io, srpLogin: deps.srpLogin })
196
+ const claims = decodeJwt(tokens.idToken)
197
+ if (claims.iss !== doc.issuer) throw new Error(`login token issuer ${claims.iss} does not match deployment ${deploymentId} (${doc.issuer})`)
198
+ if (!doc.audience.includes(claims.aud)) throw new Error(`login token audience ${claims.aud} is not a client of deployment ${deploymentId}`)
199
+ const profile = creds.setDeploymentProfile({
200
+ deploymentId,
201
+ serviceInstance: instance || 'default',
202
+ environment,
203
+ project,
204
+ userId: claims.sub,
205
+ suid: claims['custom:suid'] || null,
206
+ email: claims.email || email,
207
+ issuer: doc.issuer,
208
+ audience: doc.audience,
209
+ clientId: doc.clientId,
210
+ region: doc.region,
211
+ userPoolId: doc.userPoolId,
212
+ usersApiBase: doc.usersApiBase,
213
+ permissionsApiBase: doc.permissionsApiBase,
214
+ idToken: tokens.idToken,
215
+ accessToken: tokens.accessToken,
216
+ refreshToken: tokens.refreshToken,
217
+ expiresAt: Math.floor(Date.now() / 1000) + (Number(tokens.expiresIn) || 3600),
218
+ })
219
+ return { deploymentId, serviceInstance: profile.serviceInstance, environment, email: profile.email, userId: profile.userId }
220
+ }
221
+
59
222
  // Create a SaaSLayer account via the control-plane signup endpoint (allowlist-gated), then log in.
60
223
  async function signup(flags = {}) {
61
- const base = flags['config-url'] || process.env.SAASLAYER_CONFIG_URL
62
- if (!base) throw new Error('signup requires --config-url <control-plane API base> (or $SAASLAYER_CONFIG_URL)')
224
+ const base = String(controlPlaneUrl(flags).value).replace(/\/$/, '')
63
225
  const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
64
226
  const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Choose a password: ', { hidden: true }))
65
- const res = await fetch(`${String(base).replace(/\/$/, '')}/api/signup`, {
227
+ const res = await fetch(`${base}/api/signup`, {
66
228
  method: 'POST',
67
229
  headers: { 'content-type': 'application/json' },
68
230
  body: JSON.stringify({ email, password }),
@@ -79,9 +241,21 @@ function whoami() {
79
241
  return { userId: current.userId, email: current.email, env: current.env }
80
242
  }
81
243
 
244
+ /**
245
+ * Clear one login on the selected authority. With --deployment (and --as / --user-service-instance) the matching
246
+ * deployment login is removed; otherwise the control-plane account (--user accepts an email or a userId; without it,
247
+ * the active account). The other authority's logins are kept.
248
+ * @param {Record<string, any>} flags
249
+ * @returns {{ authority: 'deployment', deploymentId: string, email: string|null } | { authority: 'control-plane' }}
250
+ */
82
251
  function logout(flags = {}) {
83
- // --user accepts an email or a userId; without it, the active account is cleared.
252
+ if (flags.deployment || flags.as || flags['user-service-instance']) {
253
+ const profile = creds.selectDeploymentProfile(flags)
254
+ creds.clearDeploymentProfile(profile.key)
255
+ return { authority: 'deployment', deploymentId: profile.deploymentId, email: profile.email }
256
+ }
84
257
  creds.clear(flags.user ? creds.resolve(flags.user) : undefined)
258
+ return { authority: 'control-plane' }
85
259
  }
86
260
 
87
- module.exports = { login, signup, whoami, logout }
261
+ module.exports = { login, loginDeployment, authenticate, tokensFromStep, signup, whoami, logout, prompt }
@@ -0,0 +1,96 @@
1
+ // `saaslayer permissions machine-trust list|get|declare|update|remove|reconcile`: the deployment's trusted AWS IAM roles
2
+ // through the permissions machine-trust API (access-admin login, API key or IAM) — never a direct SSM write.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { permissionsRequest } = require('../permissions-request')
6
+
7
+ /**
8
+ * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string,
9
+ * 'role-arn'?: string, scope?: string|string[], 'expected-revision'?: string, 'dry-run'?: boolean }} MachineTrustFlags
10
+ * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
11
+ */
12
+
13
+ /** @param {string} label @param {string[]} positional */
14
+ function principalIdOf(label, positional) {
15
+ if (!positional[0]) throw new Error(`${label}: <principalId> is required`)
16
+ return positional[0]
17
+ }
18
+
19
+ /** @param {MachineTrustFlags} flags @returns {string[]|undefined} */
20
+ function scopesOf(flags) {
21
+ if (flags.scope === undefined) return undefined
22
+ return Array.isArray(flags.scope) ? flags.scope : [flags.scope]
23
+ }
24
+
25
+ /** Call a machine-trust route; throws with the API's codes and messages. */
26
+ const call = permissionsRequest
27
+
28
+ /** @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps] */
29
+ async function machineTrustList(positional, flags, deps = {}) {
30
+ const body = await call('permissions machine-trust list', flags, deps, 'GET', '/machine-trust')
31
+ return (body.data || []).map((d) => d.attributes)
32
+ }
33
+
34
+ /** @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps] */
35
+ async function machineTrustGet(positional, flags, deps = {}) {
36
+ const id = principalIdOf('permissions machine-trust get', positional)
37
+ const body = await call('permissions machine-trust get', flags, deps, 'GET', `/machine-trust/${encodeURIComponent(id)}`)
38
+ return body.data.attributes
39
+ }
40
+
41
+ /**
42
+ * Declare a trusted role: <principalId> --role-arn ARN --scope S [--scope S2]. Creates no grant.
43
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
44
+ */
45
+ async function machineTrustDeclare(positional, flags, deps = {}) {
46
+ const label = 'permissions machine-trust declare'
47
+ const principalId = principalIdOf(label, positional)
48
+ if (!flags['role-arn']) throw new Error(`${label}: --role-arn <arn> is required`)
49
+ const scopeCeiling = scopesOf(flags)
50
+ if (!scopeCeiling) throw new Error(`${label}: at least one --scope is required`)
51
+ const body = await call(label, flags, deps, 'POST', '/machine-trust', { principalId, roleArn: flags['role-arn'], scopeCeiling })
52
+ return { declaration: body.data.attributes, meta: body.meta || {} }
53
+ }
54
+
55
+ /**
56
+ * Change a declaration: <principalId> [--role-arn ARN] [--scope S …] [--expected-revision N].
57
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
58
+ */
59
+ async function machineTrustUpdate(positional, flags, deps = {}) {
60
+ const label = 'permissions machine-trust update'
61
+ const principalId = principalIdOf(label, positional)
62
+ const scopeCeiling = scopesOf(flags)
63
+ if (!flags['role-arn'] && !scopeCeiling) throw new Error(`${label}: give --role-arn and/or --scope`)
64
+ /** @type {{ roleArn?: string, scopeCeiling?: string[], expectedRevision?: number }} */
65
+ const patch = {}
66
+ if (flags['role-arn']) patch.roleArn = flags['role-arn']
67
+ if (scopeCeiling) patch.scopeCeiling = scopeCeiling
68
+ if (flags['expected-revision'] !== undefined) {
69
+ const n = Number(flags['expected-revision'])
70
+ if (!Number.isInteger(n)) throw new Error(`${label}: --expected-revision must be an integer`)
71
+ patch.expectedRevision = n
72
+ }
73
+ const body = await call(label, flags, deps, 'PATCH', `/machine-trust/${encodeURIComponent(principalId)}`, patch)
74
+ return { declaration: body.data.attributes, meta: body.meta || {} }
75
+ }
76
+
77
+ /**
78
+ * Remove a declaration (its mapped principal's roles are unassigned; the report lists each).
79
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
80
+ */
81
+ async function machineTrustRemove(positional, flags, deps = {}) {
82
+ const id = principalIdOf('permissions machine-trust remove', positional)
83
+ const body = await call('permissions machine-trust remove', flags, deps, 'DELETE', `/machine-trust/${encodeURIComponent(id)}`)
84
+ return body.data.attributes
85
+ }
86
+
87
+ /**
88
+ * Rewrite the deployment's backing SSM document from the declarations.
89
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
90
+ */
91
+ async function machineTrustReconcile(positional, flags, deps = {}) {
92
+ const body = await call('permissions machine-trust reconcile', flags, deps, 'POST', '/machine-trust/actions/reconcile', {})
93
+ return body.data.attributes
94
+ }
95
+
96
+ module.exports = { machineTrustList, machineTrustGet, machineTrustDeclare, machineTrustUpdate, machineTrustRemove, machineTrustReconcile }