saaslayer 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +105 -16
  2. package/bin/saaslayer.js +321 -60
  3. package/package.json +3 -2
  4. package/src/aws-sigv4.js +74 -26
  5. package/src/commands/access-admins.js +2 -2
  6. package/src/commands/admin-allowlist.js +23 -3
  7. package/src/commands/api-keys.js +83 -0
  8. package/src/commands/audit.js +77 -0
  9. package/src/commands/aws.js +355 -82
  10. package/src/commands/binding-handoff.js +174 -0
  11. package/src/commands/bindings.js +111 -0
  12. package/src/commands/catalog.js +30 -3
  13. package/src/commands/deploy.js +33 -10
  14. package/src/commands/env-export.js +58 -0
  15. package/src/commands/first-admin.js +15 -4
  16. package/src/commands/foundation.js +75 -117
  17. package/src/commands/hooks.js +271 -0
  18. package/src/commands/integration-credentials.js +1 -1
  19. package/src/commands/lifecycle.js +149 -24
  20. package/src/commands/login-domain.js +259 -0
  21. package/src/commands/permission-orgs.js +80 -0
  22. package/src/commands/release-manifest.js +17 -8
  23. package/src/commands/service-principals.js +42 -5
  24. package/src/commands/settings.js +21 -5
  25. package/src/commands/sms-registration.js +182 -0
  26. package/src/commands/sms.js +178 -0
  27. package/src/commands/social.js +265 -0
  28. package/src/commands/support-staff.js +72 -0
  29. package/src/commands/users-management.js +2 -20
  30. package/src/commands/users.js +56 -11
  31. package/src/commands/versions.js +61 -0
  32. package/src/connection-proof.js +41 -0
  33. package/src/deployments.js +1 -1
  34. package/src/foundation-change-set.js +180 -0
  35. package/src/foundation-home.js +121 -0
  36. package/src/foundation-template.js +51 -10
  37. package/src/foundation-trust-write.js +379 -0
  38. package/src/iam-session.js +14 -8
  39. package/src/login-domain.js +139 -0
  40. package/src/login-methods.js +118 -0
  41. package/src/module-catalog.js +3 -2
  42. package/src/release-manifest.js +11 -4
  43. package/src/scope.js +3 -1
  44. package/src/settings.js +85 -13
  45. package/src/sms/number.js +37 -0
  46. package/src/sms/registration-fields.js +167 -0
  47. package/src/sms/registration-validate.js +151 -0
  48. package/src/sms/registration.js +216 -0
  49. package/src/sms/release.js +55 -0
  50. package/src/sms/scope.js +86 -0
  51. package/src/sms/status.js +181 -0
  52. package/src/ssm-api.js +31 -0
  53. package/src/trust-entries.js +350 -0
  54. package/src/user-service-instance.js +27 -0
  55. package/src/users-api.js +55 -8
  56. package/src/users-import/checkpoint.js +76 -0
  57. package/src/users-import/import.js +233 -24
  58. package/src/versions.js +80 -0
  59. package/templates/saaslayer-foundation-region.yml +45 -1
  60. package/templates/saaslayer-foundation.yml +747 -296
@@ -0,0 +1,265 @@
1
+ // `saaslayer social status|enable|rotate-secret|disable <provider>`: read one user-service instance's social sign-in
2
+ // settings, or change them as ONE social configuration (POST /api/deployments/{id}/social), then wait for its run.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { apiCall } = require('../api-client')
6
+ const { resolveDeployment } = require('../deployments')
7
+ const { finishMutation, resumeCommand } = require('./operations')
8
+ const { PROTECTED_ENVS } = require('../settings')
9
+ const { chooseInstance, refOf } = require('../user-service-instance')
10
+ const { redirectUrisOf } = require('./login-domain')
11
+
12
+ const USAGE = 'usage: saaslayer social <status|enable|rotate-secret|disable> [google] [--env E] [--service REF] … (see saaslayer --help)'
13
+ // The providers this command configures, with the setting-name prefix their settings carry.
14
+ const PROVIDERS = { google: { name: 'Google', prefix: 'Google' } }
15
+ // Transient answers a request is sent again for, with the same request key: the deployer answers the same run.
16
+ const RETRIED_STATUSES = new Set([502, 504])
17
+ const ATTEMPTS = 3
18
+ // Login-domain states in which the custom host serves sign-in, so its redirect URI must be registered too.
19
+ const SERVING_LOGIN_DOMAIN_STATES = new Set(['provisioning', 'provisioned', 'active', 'deactivating'])
20
+
21
+ /** @param {unknown} value a CSV setting @returns {string[]} */
22
+ const csv = (value) => (typeof value === 'string' ? value.split(',').map((s) => s.trim()).filter(Boolean) : [])
23
+ /** @param {unknown} value a repeatable flag @returns {string[]|undefined} */
24
+ const list = (value) => (value === undefined ? undefined : (Array.isArray(value) ? value : [value]).map(String))
25
+ /** @param {unknown} value a boolean-ish setting */
26
+ const truthy = (value) => value === true || value === 'true'
27
+
28
+ /** A login host from a Cognito domain output: a custom host as is, a prefix domain in the region. @param {unknown} domain @param {string|undefined} region */
29
+ const cognitoHost = (domain, region) => (domain ? (String(domain).includes('.') ? String(domain) : `${domain}.auth.${region || 'us-east-1'}.amazoncognito.com`) : null)
30
+
31
+ /**
32
+ * The redirect URIs a provider console needs for an instance, labelled: the advertised host's (active), then any other
33
+ * host that serves sign-in (a pending custom domain, the opaque prefix domain).
34
+ * @param {Record<string, any>} instance @param {string|undefined} region
35
+ * @param {Record<string, any>|null} loginDomain the instance's login-domain status, when the control plane has one
36
+ */
37
+ function labelledRedirectUris(instance, region, loginDomain) {
38
+ const outputs = instance.outputs || {}
39
+ const pending = loginDomain && SERVING_LOGIN_DOMAIN_STATES.has(loginDomain.state) ? loginDomain.host : null
40
+ return redirectUrisOf({ activeHost: cognitoHost(outputs.UserPoolDomainName, region), host: pending, opaqueHost: cognitoHost(outputs.OpaqueLoginDomainName, region) })
41
+ }
42
+
43
+ /**
44
+ * The callback URLs registered in only one trailing-slash form, each with the form that is missing. The sign-in widget
45
+ * returns to `origin + pathname` of its page, so a bare origin is always sent as `origin/`; a file-like path or a URL
46
+ * with a query or fragment has no other form a site serves.
47
+ * @param {string[]} urls @returns {Array<{ url: string, twin: string }>}
48
+ */
49
+ function slashTwinsMissing(urls) {
50
+ const registered = new Set(urls)
51
+ return urls.flatMap((url) => {
52
+ let parsed
53
+ try { parsed = new URL(url) } catch { return [] }
54
+ if (parsed.search || parsed.hash || /\.[A-Za-z0-9]+$/.test(parsed.pathname)) return []
55
+ if (parsed.pathname === '/' && url.endsWith('/')) return []
56
+ const twin = url.endsWith('/') ? url.slice(0, -1) : `${url}/`
57
+ return registered.has(twin) ? [] : [{ url, twin }]
58
+ })
59
+ }
60
+
61
+ const SLASH_WARNING = ' warning: the sign-in widget returns to the exact address of its page, and Cognito refuses a callback URL that is not registered character for character ("RedirectUri is not registered with the client", shown only after the provider\'s sign-in). Register each page at the address the site serves it, trailing slash included:'
62
+
63
+ /**
64
+ * What the instance's settings say about social sign-in, and the values its provider console needs.
65
+ * @param {string} deploymentId
66
+ * @param {string|undefined} region
67
+ * @param {Record<string, any>} instance the instance's module in the deployment detail (its ref and outputs)
68
+ * @param {Record<string, unknown>} params the instance's setting values, as `settings get` reads them
69
+ * @param {Array<{ uri: string }>} redirectUris every redirect URI to register, the advertised host's first
70
+ */
71
+ function statusOf(deploymentId, region, instance, params, redirectUris = []) {
72
+ const host = cognitoHost((instance.outputs || {}).UserPoolDomainName, region)
73
+ const providers = Object.fromEntries(Object.entries(PROVIDERS).map(([provider, { prefix }]) => [provider, {
74
+ enabled: truthy(params[`Enable${prefix}Login`]),
75
+ clientId: typeof params[`${prefix}ClientId`] === 'string' && params[`${prefix}ClientId`] ? params[`${prefix}ClientId`] : null,
76
+ hostedDomains: csv(params[`${prefix}HostedDomains`]),
77
+ }]))
78
+ return {
79
+ deploymentId,
80
+ service: refOf(/** @type {any} */ (instance)),
81
+ providers,
82
+ callbackUrls: csv(params.AllowedCallbackUrls),
83
+ logoutUrls: csv(params.AllowedLogoutUrls),
84
+ appOrigins: csv(params.AllowedAppOrigins),
85
+ redirectUri: host ? `https://${host}/oauth2/idpresponse` : null,
86
+ authOrigin: host ? `https://${host}` : null,
87
+ redirectUris: redirectUris.map(({ uri }) => uri),
88
+ }
89
+ }
90
+
91
+ /**
92
+ * @param {ReturnType<typeof statusOf>} status @param {string|undefined} region
93
+ * @param {Array<{ uri: string, label: string }>} [others] the redirect URIs besides the advertised host's
94
+ */
95
+ function formatStatus(status, region, others = []) {
96
+ const shown = (items) => (items.length ? items.join(', ') : '—')
97
+ const lines = [`${status.service} on deployment ${status.deploymentId} (${region})`]
98
+ for (const [provider, p] of Object.entries(status.providers)) {
99
+ lines.push(` ${provider}: ${p.enabled ? 'enabled' : 'disabled'}`, ` client id: ${p.clientId || '—'}`, ` hosted domains: ${shown(p.hostedDomains)}`)
100
+ }
101
+ lines.push(` callback URLs: ${shown(status.callbackUrls)}`)
102
+ const missing = slashTwinsMissing(status.callbackUrls)
103
+ if (missing.length) lines.push(SLASH_WARNING, ...missing.map(({ url, twin }) => ` ${url} is registered, ${twin} is not`))
104
+ lines.push(` logout URLs: ${shown(status.logoutUrls)}`, ` app origins: ${shown(status.appOrigins)}`)
105
+ if (status.redirectUri) {
106
+ lines.push(' Google console (APIs & Services -> Credentials):', ` Authorized redirect URI: ${status.redirectUri}`, ` Authorized JavaScript origin: ${status.authOrigin}`)
107
+ lines.push(...others.map(({ uri, label }) => ` also keep registered (${label}): ${uri}`))
108
+ }
109
+ else lines.push(' redirect URI unavailable: deploy this user-service instance first so its Cognito domain exists')
110
+ return lines
111
+ }
112
+
113
+ /**
114
+ * The deployment, its chosen instance and that instance's social status.
115
+ * @param {Record<string, any>} flags
116
+ */
117
+ async function readStatus(flags) {
118
+ const deployment = await resolveDeployment(flags)
119
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}`, undefined, flags)
120
+ const detail = { deploymentId: deployment.deploymentId, ...doc.data.attributes }
121
+ const instance = chooseInstance(detail, flags)
122
+ const settingsDoc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, undefined, flags)
123
+ const settings = (settingsDoc.data.attributes.modules || []).find((m) => m.ref === refOf(instance))
124
+ const params = Object.fromEntries(((settings && settings.settings) || []).map((s) => [s.name, s.value]))
125
+ const region = detail.region || deployment.region
126
+ const redirectUris = labelledRedirectUris(instance, region, await readLoginDomain(deployment.deploymentId, refOf(instance), flags))
127
+ const others = redirectUris.filter(({ label }) => label !== 'active')
128
+ return { deployment, region, others, status: statusOf(deployment.deploymentId, region, instance, params, redirectUris) }
129
+ }
130
+
131
+ /**
132
+ * The instance's login-domain status, or null where the control plane has no login-domain route (404).
133
+ * @param {string} deploymentId @param {string} ref @param {Record<string, any>} flags
134
+ */
135
+ async function readLoginDomain(deploymentId, ref, flags) {
136
+ try {
137
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}/services/${encodeURIComponent(ref)}/login-domain`, undefined, flags)
138
+ return doc.data.attributes
139
+ } catch (err) {
140
+ if (err && err.status === 404) return null
141
+ throw err
142
+ }
143
+ }
144
+
145
+ /**
146
+ * The client secret piped on stdin (one trailing newline dropped). A terminal stdin is refused: the secret is never
147
+ * typed where it could echo, and never taken from a flag or the environment.
148
+ * @param {string} sub @param {NodeJS.ReadableStream & { isTTY?: boolean }} stdin
149
+ */
150
+ async function readSecret(sub, stdin) {
151
+ if (stdin.isTTY) throw new Error(`--client-secret-stdin reads the secret from a pipe or file, e.g. saaslayer social ${sub} google --client-secret-stdin < secret.txt`)
152
+ let data = ''
153
+ for await (const chunk of stdin) data += chunk
154
+ const secret = data.replace(/\r?\n$/, '')
155
+ if (!secret) throw new Error('the client secret on stdin is empty')
156
+ return secret
157
+ }
158
+
159
+ /**
160
+ * Send one social configuration, retrying a dropped connection with the same request and request key.
161
+ * @param {string} deploymentId @param {object} attributes @param {Record<string, any>} flags @param {{ retryDelayMs: number }} opts
162
+ */
163
+ async function sendConfiguration(deploymentId, attributes, flags, { retryDelayMs }) {
164
+ const body = { data: { type: 'social-configurations', attributes }, meta: { idempotencyKey: `cli-${crypto.randomUUID()}` } }
165
+ for (let attempt = 1; ; attempt += 1) {
166
+ try {
167
+ return await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/social`, body, flags)
168
+ } catch (err) {
169
+ const transient = err.status === undefined || RETRIED_STATUSES.has(err.status)
170
+ if (!transient || attempt >= ATTEMPTS) throw err
171
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs * attempt))
172
+ }
173
+ }
174
+ }
175
+
176
+ /**
177
+ * A refusal as `<code>: <title>` plus the next step it needs; with --json the refusal document is printed as is.
178
+ * @param {any} err @param {Record<string, any>} flags
179
+ */
180
+ function refusalOf(err, flags) {
181
+ const first = err && err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
182
+ if (!first) return err
183
+ if (flags.json) console.log(JSON.stringify({ errors: err.body.errors }, null, 2))
184
+ let message = `${first.code || err.status}: ${first.title || first.detail || 'request refused'}`
185
+ if (first.code === 'SOCIAL_ONLY_USERS_AFFECTED') message += '\neach of them needs another sign-in method first (a signed-in user can add a password from their profile); `saaslayer social status` shows the instance'
186
+ return Object.assign(new Error(message), { status: err.status, body: err.body })
187
+ }
188
+
189
+ /**
190
+ * The provider attributes for a change; refusals happen before anything is sent.
191
+ * @param {'enable'|'rotate-secret'|'disable'} sub @param {string} provider @param {ReturnType<typeof statusOf>} status
192
+ * @param {Record<string, any>} flags @param {{ stdin: NodeJS.ReadableStream }} deps
193
+ */
194
+ async function providerChange(sub, provider, status, flags, deps) {
195
+ const current = status.providers[provider]
196
+ if (sub === 'disable') return { enabled: false }
197
+ if (sub === 'rotate-secret' && !flags['client-secret-stdin']) throw new Error(`social rotate-secret ${provider} needs --client-secret-stdin`)
198
+ if (sub === 'rotate-secret' && !current.enabled) throw new Error(`${provider} is off on ${status.service}: enable it with saaslayer social enable ${provider}`)
199
+ const clientId = typeof flags['client-id'] === 'string' ? flags['client-id'] : current.clientId
200
+ if (!clientId) throw new Error(`social enable ${provider} needs --client-id <id>: ${status.service} has no ${PROVIDERS[provider].name} client id yet`)
201
+ const clientSecret = flags['client-secret-stdin'] ? await readSecret(sub, deps.stdin) : undefined
202
+ const hostedDomains = sub === 'enable' ? list(flags['hosted-domain']) : undefined
203
+ return { enabled: true, clientId, ...(clientSecret ? { clientSecret } : {}), ...(hostedDomains ? { hostedDomains } : {}) }
204
+ }
205
+
206
+ const DONE = { enable: 'enabled', 'rotate-secret': 'client secret rotated', disable: 'disabled' }
207
+
208
+ /**
209
+ * `social enable|rotate-secret|disable <provider>`: one social configuration for the chosen instance, then its run.
210
+ * @param {'enable'|'rotate-secret'|'disable'} sub @param {string|undefined} provider @param {Record<string, any>} flags
211
+ * @param {{ stdin: NodeJS.ReadableStream, retryDelayMs: number }} deps
212
+ */
213
+ async function changeSocial(sub, provider, flags, deps) {
214
+ if (!provider) throw new Error(`social ${sub} needs a provider: ${Object.keys(PROVIDERS).join(', ')}`)
215
+ if (!PROVIDERS[provider]) throw new Error(`${provider} cannot be configured here: ${Object.keys(PROVIDERS).join(', ')} is the only provider so far`)
216
+ if (flags['client-secret'] !== undefined) throw new Error('pass the client secret on stdin with --client-secret-stdin (never as a flag)')
217
+ const { deployment, status } = await readStatus(flags)
218
+ const reason = typeof flags.reason === 'string' && flags.reason.trim() ? flags.reason.trim() : undefined
219
+ if (!reason && PROTECTED_ENVS.has(deployment.env)) throw new Error(`${deployment.env} is a protected environment: pass --reason <text>`)
220
+ const change = await providerChange(sub, provider, status, flags, deps)
221
+ const callbackUrls = sub === 'enable' ? list(flags['callback-url']) : undefined
222
+ const appOrigins = sub === 'enable' ? list(flags['app-origin']) : undefined
223
+ const attributes = {
224
+ service: status.service,
225
+ providers: { [provider]: change },
226
+ ...(callbackUrls ? { callbackUrls } : {}),
227
+ ...(appOrigins ? { appOrigins } : {}),
228
+ ...(reason ? { reason } : {}),
229
+ ...(sub === 'disable' && flags.confirm === true ? { confirm: true } : {}),
230
+ }
231
+ let res
232
+ try {
233
+ res = await sendConfiguration(deployment.deploymentId, attributes, flags, deps)
234
+ } catch (err) {
235
+ throw refusalOf(err, flags)
236
+ }
237
+ const answered = res.data.attributes
238
+ // Without an operation there is nothing to wait on, so success cannot be reported.
239
+ if (typeof answered.operationId !== 'string' || !answered.operationId) {
240
+ const follow = answered.runId ? `: follow its run with \`${resumeCommand(answered.runId, deployment.deploymentId)}\`` : ''
241
+ throw new Error(`the control plane accepted the change but named no operation to wait on (run ${answered.runId || 'unknown'})${follow}`)
242
+ }
243
+ const revision = answered.secretRevisions && answered.secretRevisions[provider]
244
+ console.log(`${provider} ${DONE[sub]} on ${status.service} of ${deployment.deploymentId}: operation ${answered.operationId}${revision ? `, client secret stored as revision ${revision}` : ''}`)
245
+ return finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
246
+ }
247
+
248
+ /**
249
+ * @param {string|undefined} sub status | enable | rotate-secret | disable
250
+ * @param {string|undefined} provider
251
+ * @param {Record<string, any>} flags
252
+ * @param {{ stdin?: NodeJS.ReadableStream, retryDelayMs?: number }} [deps]
253
+ */
254
+ async function socialCommand(sub, provider, flags, deps = {}) {
255
+ const resolved = { stdin: deps.stdin || process.stdin, retryDelayMs: deps.retryDelayMs === undefined ? 1000 : deps.retryDelayMs }
256
+ if (sub === 'status') {
257
+ const { region, status, others } = await readStatus(flags)
258
+ console.log(flags.json ? JSON.stringify(status, null, 2) : formatStatus(status, region, others).join('\n'))
259
+ return status
260
+ }
261
+ if (sub === 'enable' || sub === 'rotate-secret' || sub === 'disable') return changeSocial(sub, provider, flags, resolved)
262
+ throw new Error(USAGE)
263
+ }
264
+
265
+ module.exports = { socialCommand }
@@ -0,0 +1,72 @@
1
+ // `saaslayer permissions support-staff grant|revoke|list`: the deployment's support staff, who view as members of any org
2
+ // through the reserved support roles (view-only or act-as), granted and revoked at deployment scope by an access admin in person.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const { permissionsRequest } = require('../permissions-request')
7
+
8
+ // The reserved role ids: monorepo source first (vendor/ is a prepack snapshot), else the published copy.
9
+ const MONOREPO_DELEGATION = path.join(__dirname, '../../../permissions-engine-core/src/delegation.js')
10
+ const VENDORED_DELEGATION = path.join(__dirname, '../../vendor/permissions-engine-core/delegation.js')
11
+ /** @type {typeof import('../../../permissions-engine-core/src/delegation.js')} */
12
+ const { RESERVED_ROLES } = require(fs.existsSync(MONOREPO_DELEGATION) ? MONOREPO_DELEGATION : VENDORED_DELEGATION)
13
+
14
+ /** The reserved support role for each impersonation mode it allows at most. */
15
+ const ROLE_BY_MODE = Object.freeze({ 'view-only': RESERVED_ROLES.supportViewOnly.id, 'act-as': RESERVED_ROLES.supportActAs.id })
16
+
17
+ /**
18
+ * @typedef {import('../permissions-request').PermissionsFlags & { mode?: string, 'expires-at'?: string }} SupportFlags
19
+ * @typedef {import('../permissions-request').Deps} Deps
20
+ */
21
+
22
+ /** @param {string} label @param {string[]} positional */
23
+ function suidOf(label, positional) {
24
+ if (!positional[0]) throw new Error(`${label}: <suid> is required`)
25
+ return positional[0]
26
+ }
27
+
28
+ /** @param {string} label @param {SupportFlags} flags */
29
+ function roleOf(label, flags) {
30
+ const roleId = flags.mode ? ROLE_BY_MODE[/** @type {keyof typeof ROLE_BY_MODE} */ (flags.mode)] : undefined
31
+ if (!roleId) throw new Error(`${label}: --mode view-only|act-as is required`)
32
+ return roleId
33
+ }
34
+
35
+ /**
36
+ * Grant <suid> the support role for --mode (act-as also allows view-only), optionally until --expires-at.
37
+ * @param {string[]} positional @param {SupportFlags} flags @param {Deps} [deps]
38
+ */
39
+ async function supportStaffGrant(positional, flags, deps = {}) {
40
+ const label = 'permissions support-staff grant'
41
+ const suid = suidOf(label, positional)
42
+ const roleId = roleOf(label, flags)
43
+ const body = await permissionsRequest(label, flags, deps, 'POST', `/users/${encodeURIComponent(suid)}/roles`, { roleId, ...(flags['expires-at'] ? { expiresAt: flags['expires-at'] } : {}) })
44
+ return body.data.attributes
45
+ }
46
+
47
+ /**
48
+ * Revoke <suid>'s support role for --mode.
49
+ * @param {string[]} positional @param {SupportFlags} flags @param {Deps} [deps]
50
+ */
51
+ async function supportStaffRevoke(positional, flags, deps = {}) {
52
+ const label = 'permissions support-staff revoke'
53
+ const suid = suidOf(label, positional)
54
+ const roleId = roleOf(label, flags)
55
+ await permissionsRequest(label, flags, deps, 'DELETE', `/users/${encodeURIComponent(suid)}/roles/${encodeURIComponent(roleId)}`)
56
+ return { userId: suid, roleId, revoked: true }
57
+ }
58
+
59
+ /**
60
+ * Every support staff member: who, the mode their role allows at most, and its expiry.
61
+ * @param {string[]} positional @param {SupportFlags} flags @param {Deps} [deps]
62
+ */
63
+ async function supportStaffList(positional, flags, deps = {}) {
64
+ const rows = []
65
+ for (const [mode, roleId] of Object.entries(ROLE_BY_MODE)) {
66
+ const body = await permissionsRequest('permissions support-staff list', flags, deps, 'GET', `/roles/${encodeURIComponent(roleId)}/assignments`)
67
+ for (const d of body.data || []) rows.push({ userId: d.attributes.userId, mode, roleId, expiresAt: d.attributes.expiresAt || null })
68
+ }
69
+ return rows
70
+ }
71
+
72
+ module.exports = { supportStaffGrant, supportStaffRevoke, supportStaffList, ROLE_BY_MODE }
@@ -6,7 +6,7 @@ const path = require('path')
6
6
  const crypto = require('crypto')
7
7
  const { execFileSync } = require('child_process')
8
8
  const { apiCall } = require('../api-client')
9
- const { signRequest } = require('../aws-sigv4')
9
+ const { ssmApi } = require('../ssm-api')
10
10
  const { awsCredentials } = require('../iam-session')
11
11
 
12
12
  // The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
@@ -165,25 +165,7 @@ function checkedManifest(file, instance, management) {
165
165
  * @param {{ region: string, credentials: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, basePath: string, fetchImpl: typeof fetch }} deps
166
166
  */
167
167
  function ssmMaterial({ region, credentials, basePath, fetchImpl }) {
168
- const host = `ssm.${region}.amazonaws.com`
169
- /** @param {string} action @param {Record<string, unknown>} input */
170
- async function call(action, input) {
171
- const body = JSON.stringify(input)
172
- const { headers } = signRequest({
173
- method: 'POST',
174
- url: `https://${host}/`,
175
- body,
176
- region,
177
- service: 'ssm',
178
- credentials: credentials(),
179
- headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': `AmazonSSM.${action}`, Host: host },
180
- })
181
- const res = await fetchImpl(`https://${host}/`, { method: 'POST', headers, body })
182
- const doc = await res.json().catch(() => ({}))
183
- if (res.ok) return doc
184
- const type = String((doc && (doc.__type || doc.code)) || '').split('#').pop()
185
- throw Object.assign(new Error(`SSM ${action} failed (${res.status}${type ? ` ${type}` : ''})`), { name: type || 'SsmError' })
186
- }
168
+ const call = ssmApi({ region, credentials, fetchImpl })
187
169
  const name = (/** @type {string} */ keyId) => `${basePath}/${keyId}`
188
170
  return {
189
171
  async put(/** @type {string} */ keyId, /** @type {string} */ raw) {
@@ -6,8 +6,9 @@ const path = require('path')
6
6
  const { execFileSync } = require('child_process')
7
7
  const { getProvider } = require('../users-import/providers')
8
8
  const { buildManifest, validateManifest } = require('../users-import/manifest')
9
- const { planImport, applyImport, formatPlan } = require('../users-import/import')
9
+ const { planImport, applyImport, formatPlan, checkProfiles } = require('../users-import/import')
10
10
  const { mintSuid } = require('../users-import/ids')
11
+ const { checkpointPath } = require('../users-import/checkpoint')
11
12
  const { authHeaders } = require('../deployment-api-auth')
12
13
  const { exchangeIamToken } = require('../iam-session')
13
14
  const creds = require('../credentials')
@@ -39,6 +40,8 @@ async function usersExport(flags, deps = {}) {
39
40
  const users = manifest.accounts.reduce((n, a) => n + a.users.length, 0)
40
41
  log(`exported ${users} users in ${manifest.accounts.length} accounts to ${flags.out}`)
41
42
  log('The manifest holds personal data (emails, names, phones). Keep it private and delete it after the import.')
43
+ log('It holds no passwords or MFA secrets: imported users set a new password and set up MFA again.')
44
+ log('It reads one pool: a SaaSLayer deployment\'s second sign-in pool (phone or email) is not exported; those sign-ins are linked again after the import.')
42
45
  if (errors.length) log(`fix before importing:\n ${errors.join('\n ')}`)
43
46
  return manifest
44
47
  }
@@ -47,7 +50,8 @@ async function usersExport(flags, deps = {}) {
47
50
  * Dry run by default (prints the plan); --apply imports and writes a report next to the manifest (or --report).
48
51
  * @param {Record<string, any>} flags
49
52
  * @param {{ exec?: typeof defaultExec, fetch?: typeof fetch, log?: (line: string) => void, now?: () => Date,
50
- * mint?: () => string, sleep?: (ms: number) => Promise<void>, authHeaders?: () => Promise<Record<string, string>> }} [deps]
53
+ * mint?: () => string, sleep?: (ms: number) => Promise<void>, authHeaders?: () => Promise<Record<string, string>>,
54
+ * exchange?: typeof exchangeIamToken }} [deps]
51
55
  */
52
56
  async function usersImport(flags, deps = {}) {
53
57
  const { exec = defaultExec, log = console.log, now = () => new Date() } = deps
@@ -55,6 +59,8 @@ async function usersImport(flags, deps = {}) {
55
59
  const manifest = JSON.parse(fs.readFileSync(path.resolve(flags.manifest), 'utf8'))
56
60
  const errors = validateManifest(manifest)
57
61
  if (errors.length) throw new Error(`users import: the manifest is invalid:\n ${errors.join('\n ')}`)
62
+ // A --token is a Permissions API key; user-service (profiles) takes x-api-key only for its own integration credentials.
63
+ if (flags.apply && !flags.iam) throw new Error("users import --apply needs --iam: user-service (profiles) doesn't accept Permissions API keys")
58
64
  const target = {
59
65
  userPoolId: flags['user-pool-id'],
60
66
  region: flags.region || process.env.AWS_REGION,
@@ -62,23 +68,37 @@ async function usersImport(flags, deps = {}) {
62
68
  apiBase: flags['api-base'] || process.env.SAASLAYER_API_BASE,
63
69
  product: flags.product,
64
70
  logsRoleArn: flags['logs-role-arn'],
71
+ iam: flags.iam,
72
+ checkpointFile: path.resolve(checkpointPath(flags.manifest)),
65
73
  }
66
74
  const plan = await planImport(manifest, target, { exec })
67
75
  log(formatPlan(plan, { apply: Boolean(flags.apply) }))
68
- if (!flags.apply) return { plan }
69
- const report = await applyImport(plan, target, {
76
+ const io = {
70
77
  exec,
71
78
  fetch: deps.fetch || fetch,
79
+ authHeaders: deps.authHeaders || (() => authHeaders(target.apiBase, flags, { exchange: deps.exchange || exchangeIamToken })),
80
+ }
81
+ if (!flags.apply) {
82
+ if (!flags.iam) log('profiles are checked and created at --apply (needs --iam)')
83
+ else for (const line of await checkProfiles(plan, target, io)) log(line)
84
+ return { plan }
85
+ }
86
+ const report = await applyImport(plan, target, {
87
+ ...io,
72
88
  mint: deps.mint || mintSuid,
73
89
  sleep: deps.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
74
- authHeaders: deps.authHeaders || (() => authHeaders(target.apiBase, flags, { exchange: exchangeIamToken })),
75
90
  now,
76
91
  })
77
92
  const reportPath = path.resolve(flags.report || flags.manifest.replace(/\.json$/, '') + '.import-report.json')
78
93
  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2) + '\n', { mode: 0o600 })
79
94
  const s = report.summary
80
- log(`imported: ${s.created} created, ${s.linked} linked, ${s.failed} failed, ${s.skipped} skipped; ${s.orgsCreated} orgs created, ${s.ownersGranted} owners granted`)
81
- log(`report: ${reportPath}${s.failed ? ' — re-run to retry the failed users' : ''}`)
95
+ log(`imported: ${s.created} created, ${s.linked} linked, ${s.failed} failed, ${s.skipped} skipped; ${s.orgsCreated} orgs created, ${s.ownersGranted} owners granted; ${s.profilesCreated} profiles created, ${s.profilesExisting} existing, ${s.profilesFailed} failed`)
96
+ log(`report: ${reportPath}${s.failed || s.profilesFailed ? ' — re-run to retry the failed users and profiles' : ''}`)
97
+ // Incomplete only after the report is written: the caller sets the exit code.
98
+ if (s.failed || s.profilesFailed) {
99
+ log(`incomplete: ${s.failed} users and ${s.profilesFailed} profiles need attention (see ${reportPath})`)
100
+ return { plan, report, exitCode: 1 }
101
+ }
82
102
  return { plan, report }
83
103
  }
84
104
 
@@ -145,8 +165,11 @@ async function targetSuid(command, args, flags, api) {
145
165
  throw new Error(`users ${command}: <suid>, --suid or --email is required`)
146
166
  }
147
167
 
148
- /** --attr name=value (repeatable) plus --name, as profile attributes. @param {Record<string, any>} flags */
149
- function profileAttributes(flags) {
168
+ // Attributes only the user service's reserved-attributes route changes (it needs saaslayer:users:account:update-reserved).
169
+ const RESERVED_ATTRIBUTES = ['email', 'email_verified', 'soid']
170
+
171
+ /** --attr name=value (repeatable) plus --name, as written. @param {Record<string, any>} flags */
172
+ function updateAttributes(flags) {
150
173
  /** @type {Record<string, string>} */
151
174
  const attrs = flags.name ? { name: String(flags.name) } : {}
152
175
  for (const pair of [].concat(flags.attr || [])) {
@@ -158,6 +181,27 @@ function profileAttributes(flags) {
158
181
  return attrs
159
182
  }
160
183
 
184
+ /**
185
+ * The update as one request: profile attributes, or reserved ones (email_verified typed as a boolean). A mix is refused
186
+ * before any request, so it is never mistaken for one atomic change.
187
+ * @param {Record<string, string>} attrs
188
+ * @returns {{ reserved: false, attributes: Record<string, string> } | { reserved: true, attributes: Record<string, string|boolean> }}
189
+ */
190
+ function updateRequest(attrs) {
191
+ const names = Object.keys(attrs)
192
+ const reserved = names.filter((n) => RESERVED_ATTRIBUTES.includes(n))
193
+ if (!reserved.length) return { reserved: false, attributes: attrs }
194
+ const profile = names.filter((n) => !RESERVED_ATTRIBUTES.includes(n))
195
+ if (profile.length) throw new Error(`users update: profile attributes (${profile.join(', ')}) and reserved attributes (${reserved.join(', ')}) are separate requests; run them as two updates`)
196
+ /** @type {Record<string, string|boolean>} */
197
+ const typed = { ...attrs }
198
+ if ('email_verified' in attrs) {
199
+ if (attrs.email_verified !== 'true' && attrs.email_verified !== 'false') throw new Error(`users update: email_verified must be true or false, got ${attrs.email_verified}`)
200
+ typed.email_verified = attrs.email_verified === 'true'
201
+ }
202
+ return { reserved: true, attributes: typed }
203
+ }
204
+
161
205
  /**
162
206
  * Create a user (a durable operation). --password-stdin gives a permanent password (password initialization: never
163
207
  * prod); --delivery invitation mails a temporary one. Re-running the same command replays the same operation (the
@@ -223,8 +267,9 @@ const HANDLERS = {
223
267
  return api.list({ email: flags.email, defaultOrg: flags['default-org'] }, { limit: flags.limit, cursor: flags.cursor })
224
268
  },
225
269
  update: async (api, args, flags) => {
226
- const attributes = profileAttributes(flags)
227
- return api.update(await targetSuid('update', args, flags, api), attributes)
270
+ const request = updateRequest(updateAttributes(flags))
271
+ const suid = await targetSuid('update', args, flags, api)
272
+ return request.reserved ? api.updateReserved(suid, request.attributes) : api.update(suid, request.attributes)
228
273
  },
229
274
  disable: async (api, args, flags) => api.disable(await targetSuid('disable', args, flags, api)),
230
275
  enable: async (api, args, flags) => api.enable(await targetSuid('enable', args, flags, api)),
@@ -0,0 +1,61 @@
1
+ // `saaslayer versions [--project P] [--json]`: the versions a deployment may move to (GET /api/versions), highest first,
2
+ // with the channels on each, breaking releases flagged and, with a project, which of its deployments run each one.
3
+ 'use strict'
4
+ const { apiCall } = require('../api-client')
5
+ const { resolveScope, printScope } = require('../scope')
6
+ const { fetchVersions } = require('../versions')
7
+
8
+ /**
9
+ * The project's live deployments by environment, or null when no project is selected.
10
+ * @param {object} flags
11
+ * @returns {Promise<Array<{ label: string, version: string|null, commitSha: string|null }>|null>}
12
+ */
13
+ async function projectDeployments(flags) {
14
+ let scope
15
+ try {
16
+ scope = resolveScope(flags, { env: 'all' })
17
+ } catch {
18
+ return null
19
+ }
20
+ printScope(scope, flags)
21
+ const view = await apiCall('GET', `/api/projects/${encodeURIComponent(scope.project.value)}/deployments`, undefined, flags)
22
+ return (view.environments || []).flatMap((g) => (g.instances || []).map((i) => ({
23
+ label: `${g.environment}${i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''}`,
24
+ version: i.version || null,
25
+ commitSha: i.commitSha || null,
26
+ })))
27
+ }
28
+
29
+ /**
30
+ * @param {object} flags
31
+ * @returns {Promise<Array<import('../versions').Version & { deployments: string[] }>>}
32
+ */
33
+ async function versions(flags) {
34
+ const list = await fetchVersions(flags)
35
+ const deployments = await projectDeployments(flags)
36
+ const rows = list.map((v) => ({ ...v, deployments: (deployments || []).filter((d) => d.version === v.version).map((d) => d.label) }))
37
+ if (flags.json) {
38
+ console.log(JSON.stringify(rows, null, 2))
39
+ return rows
40
+ }
41
+ if (!rows.length) {
42
+ console.log('no versions yet: SaaSLayer has not published one for this control plane')
43
+ return rows
44
+ }
45
+ const width = Math.max(...rows.map((r) => r.version.length))
46
+ const channelWidth = Math.max(1, ...rows.map((r) => (r.channels.length ? r.channels.join(',') : '—').length))
47
+ console.log('Versions (highest first):')
48
+ for (const r of rows) {
49
+ const channels = (r.channels.length ? r.channels.join(',') : '—').padEnd(channelWidth)
50
+ const on = r.deployments.length ? ` ← ${r.deployments.join(', ')}` : ''
51
+ console.log(` ${r.version.padEnd(width)} ${channels} ${r.compat.padEnd(12)} ${(r.cutAt || '').slice(0, 10)}${on}`)
52
+ }
53
+ const known = new Set(rows.map((r) => r.version))
54
+ const off = (deployments || []).filter((d) => !d.version || !known.has(d.version))
55
+ if (off.length) console.log(` not on a version: ${off.map((d) => `${d.label} (${d.version || (d.commitSha ? d.commitSha.slice(0, 8) : '—')})`).join(', ')}`)
56
+ console.log('')
57
+ console.log('Move a deployment with: saaslayer update --version <version> [--env E] (or --channel stable)')
58
+ return rows
59
+ }
60
+
61
+ module.exports = { versions }
@@ -0,0 +1,41 @@
1
+ // Org connection proof for `saaslayer aws connect` (ADR 0005 §4): an sts:GetCallerIdentity request presigned with the
2
+ // caller's AWS credentials for 15 minutes, signing X-SaaSLayer-Connection-Binding: <orgId>:<controlPlaneId>:<scope>:<nonce>.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { presignUrl } = require('./aws-sigv4')
6
+
7
+ /** The signed header that binds the proof to one org, control plane and scope. */
8
+ const BINDING_HEADER = 'X-SaaSLayer-Connection-Binding'
9
+ /** A proof is valid at most 15 minutes (the control plane refuses longer). */
10
+ const PROOF_SECONDS = 900
11
+
12
+ /**
13
+ * The connection scope a proof binds: `org`, or `projects:<id>` when one project is named and the connect is not org-wide.
14
+ * @param {{ orgWide?: boolean, projectId?: string }} input
15
+ * @returns {string}
16
+ */
17
+ function proofScope({ orgWide, projectId }) {
18
+ return orgWide || !projectId ? 'org' : `projects:${projectId}`
19
+ }
20
+
21
+ /**
22
+ * A fresh connection proof. The presigned URL carries the caller's session token: never log or persist it.
23
+ * @param {{ orgId: string, controlPlaneId: string, scope: string, region: string,
24
+ * credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date, nonce?: string }} input
25
+ * @returns {{ presignedUrl: string, binding: string }}
26
+ */
27
+ function buildConnectionProof({ orgId, controlPlaneId, scope, region, credentials, now = new Date(), nonce = crypto.randomBytes(16).toString('hex') }) {
28
+ const binding = `${orgId}:${controlPlaneId}:${scope}:${nonce}`
29
+ const presignedUrl = presignUrl({
30
+ url: `https://sts.${region}.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15`,
31
+ headers: { [BINDING_HEADER]: binding },
32
+ region,
33
+ service: 'sts',
34
+ expires: PROOF_SECONDS,
35
+ credentials,
36
+ now,
37
+ })
38
+ return { presignedUrl, binding }
39
+ }
40
+
41
+ module.exports = { BINDING_HEADER, PROOF_SECONDS, proofScope, buildConnectionProof }
@@ -20,7 +20,7 @@ async function resolveDeployment(flags) {
20
20
  }
21
21
  if (instances.length > 1) throw new Error(`multiple ${env} deployments — pass --region <r>: ${instances.map((i) => i.region).join(', ')}`)
22
22
  const inst = instances[0]
23
- return { project, env, region: inst.region, deploymentId: inst.deploymentId, status: inst.status }
23
+ return { project, env, region: inst.region, deploymentId: inst.deploymentId, status: inst.status, commitSha: inst.commitSha || null, version: inst.version || null }
24
24
  }
25
25
 
26
26
  module.exports = { resolveDeployment }