saaslayer 0.0.7 → 0.1.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 (44) hide show
  1. package/README.md +150 -13
  2. package/bin/saaslayer.js +297 -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/catalog.js +30 -29
  10. package/src/commands/context.js +64 -0
  11. package/src/commands/deploy.js +79 -10
  12. package/src/commands/first-admin.js +42 -0
  13. package/src/commands/foundation.js +405 -0
  14. package/src/commands/lifecycle.js +72 -39
  15. package/src/commands/login.js +200 -26
  16. package/src/commands/machine-trust.js +96 -0
  17. package/src/commands/operations.js +140 -0
  18. package/src/commands/orgs.js +29 -4
  19. package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
  20. package/src/commands/release-manifest.js +138 -0
  21. package/src/commands/service-principals.js +81 -0
  22. package/src/commands/settings.js +140 -0
  23. package/src/commands/stacks.js +12 -7
  24. package/src/commands/users.js +192 -4
  25. package/src/config.js +20 -7
  26. package/src/credentials.js +221 -34
  27. package/src/deployment-api-auth.js +61 -0
  28. package/src/deployment-auth.js +38 -0
  29. package/src/deployments.js +12 -13
  30. package/src/discovery.js +66 -0
  31. package/src/env-compare.js +143 -0
  32. package/src/iam-session.js +4 -30
  33. package/src/module-catalog.js +66 -0
  34. package/src/permissions-request.js +43 -0
  35. package/src/release-manifest.js +334 -0
  36. package/src/scope.js +114 -0
  37. package/src/settings.js +272 -0
  38. package/src/users-api.js +165 -0
  39. package/src/users-import/import.js +10 -10
  40. package/templates/saaslayer-foundation.yml +23 -6
  41. package/src/commands/iam-principals.js +0 -53
  42. package/src/rbac-auth.js +0 -25
  43. package/vendor/ids/index.d.ts +0 -21
  44. package/vendor/ids/index.js +0 -237
@@ -0,0 +1,138 @@
1
+ // `saaslayer update --manifest FILE` (preflight, then move the release through /update and write the environment's
2
+ // settings through the settings route) and `saaslayer release-manifest create` (record a tested deployment's release).
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const { apiCall } = require('../api-client')
6
+ const { finishMutation, requestKeyHeaders } = require('./operations')
7
+ const { applySettings, fetchSchema, readDeploymentSettings } = require('./settings')
8
+ const { formatChanges } = require('../settings')
9
+ const rm = require('../release-manifest')
10
+ const { version: CLI_VERSION } = require('../../package.json')
11
+
12
+ const USAGE = 'usage: saaslayer release-manifest create --env E [--out FILE] [--name NAME] (see saaslayer --help)'
13
+
14
+ /** @param {object} flags @param {string} name */
15
+ const flagOn = (flags, name) => flags[name] === true || flags[name] === 'true'
16
+
17
+ /**
18
+ * Each bundle module's contract at the bundle revision, or the error code that kept it out.
19
+ * @param {rm.ReleaseManifest} manifest @param {object} flags
20
+ * @returns {Promise<Record<string, { schema?: import('../settings').SettingsSchema, error?: string }>>}
21
+ */
22
+ async function fetchTargetSchemas(manifest, flags) {
23
+ const entries = await Promise.all(Object.keys(manifest.bundle.modules).map(async (module) => {
24
+ try {
25
+ return [module, { schema: await fetchSchema(module, manifest.bundle.revision, flags) }]
26
+ } catch (err) {
27
+ if (!err.status || err.status >= 500) throw err
28
+ const code = err.body && err.body.errors && err.body.errors[0] && err.body.errors[0].code
29
+ return [module, { error: code || `HTTP ${err.status}` }]
30
+ }
31
+ }))
32
+ return Object.fromEntries(entries)
33
+ }
34
+
35
+ /**
36
+ * `update --manifest FILE [--env E] [--settings F] [--reason T] [--force] [--dry-run] [--no-wait]`. Refuses on any
37
+ * preflight problem before anything is sent.
38
+ * @param {object} flags
39
+ */
40
+ async function updateFromManifest(flags) {
41
+ if (flags['commit-sha'] !== undefined || flags.commitSha !== undefined || flags.param !== undefined) {
42
+ throw new Error('--manifest sets the release and settings: drop --commit-sha and --param')
43
+ }
44
+ const file = flags.manifest
45
+ if (typeof file !== 'string') throw new Error('update --manifest needs a release manifest file')
46
+ const manifest = rm.readManifest(file)
47
+ const { deployment, settings } = await readDeploymentSettings(flags)
48
+ const env = deployment.env
49
+ const envPatch = rm.environmentSettings(manifest, file, env, flags.settings)
50
+ const result = rm.preflightManifest({
51
+ manifest,
52
+ env,
53
+ current: settings,
54
+ targetSchemas: await fetchTargetSchemas(manifest, flags),
55
+ envPatch,
56
+ reason: typeof flags.reason === 'string' ? flags.reason : undefined,
57
+ cliVersion: CLI_VERSION,
58
+ noWait: flagOn(flags, 'no-wait'),
59
+ })
60
+ const target = manifest.bundle.revision
61
+ const where = `${env} (${deployment.deploymentId})`
62
+ if (!result.ok) {
63
+ const lines = result.problems.map((p) => ` - ${p.code}: ${p.message}${p.action ? `\n → ${p.action}` : ''}`)
64
+ throw new Error(`preflight ${where} failed — nothing was changed:\n${lines.join('\n')}`)
65
+ }
66
+ console.log(`preflight ${where}: ok${manifest.name ? ` (${manifest.name})` : ''}`)
67
+ console.log(` release: ${result.fromRevisions.map((r) => r.slice(0, 7)).join(', ')} → ${target.slice(0, 7)}${result.moveRelease ? '' : ' (already deployed)'}`)
68
+ if (result.patch) for (const line of formatChanges(result.patch, settings)) console.log(line)
69
+ else console.log(` settings: ${envPatch ? 'match' : `none named for ${env}`}`)
70
+ if (flagOn(flags, 'dry-run')) {
71
+ console.log('[dry-run] nothing was changed')
72
+ return result
73
+ }
74
+ if (!result.moveRelease && !result.patch) {
75
+ console.log(`${deployment.deploymentId} already runs ${target.slice(0, 7)} and its settings match: nothing to change`)
76
+ return result
77
+ }
78
+ if (result.moveRelease) {
79
+ const attributes = { commitSha: target }
80
+ if (flags.reason) attributes.reason = flags.reason
81
+ if (flagOn(flags, 'force')) attributes.force = true
82
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
83
+ console.log(`✅ release move to ${target.slice(0, 7)} started for ${deployment.deploymentId}`)
84
+ await finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
85
+ }
86
+ if (result.patch) await applySettings(result.patch, flags)
87
+ return result
88
+ }
89
+
90
+ /**
91
+ * `release-manifest create --env E [--out FILE] [--name NAME]`: the revision, settings-contract hashes and permissions writer
92
+ * declaration of a tested deployment, and this CLI's version. Reader declarations and environment settings are left
93
+ * for the author: a missing reader declaration is never inferred.
94
+ * @param {object} flags
95
+ */
96
+ async function createManifest(flags) {
97
+ const { deployment, settings } = await readDeploymentSettings(flags)
98
+ const revisions = [...new Set(settings.modules.map((m) => m.revision))]
99
+ if (revisions.length !== 1 || !revisions[0]) {
100
+ throw new Error(`${deployment.deploymentId} runs more than one revision (${settings.modules.map((m) => `${m.module}@${(m.revision || '—').slice(0, 7)}`).join(', ')}): update it to one tested release first`)
101
+ }
102
+ const revision = /** @type {string} */ (revisions[0])
103
+ /** @type {Record<string, { settingsContractSha256: string }>} */
104
+ const modules = {}
105
+ for (const m of settings.modules) modules[m.module] = { settingsContractSha256: rm.contractHash(await fetchSchema(m.module, revision, flags)) }
106
+ const writer = settings.modules.find((m) => m.module === rm.PERMISSIONS_WRITER.module)
107
+ const docSetting = writer && writer.settings.find((s) => s.name === rm.PERMISSIONS_WRITER.permissionDocSetting)
108
+ const manifest = {
109
+ schemaVersion: rm.MANIFEST_SCHEMA_VERSION,
110
+ ...(typeof flags.name === 'string' ? { name: flags.name } : {}),
111
+ bundle: { revision, modules },
112
+ tooling: { cli: CLI_VERSION },
113
+ ...(writer ? { compatibility: { permissions: rm.permissionsWriterRelease(docSetting ? docSetting.value : undefined) } } : {}),
114
+ environments: {},
115
+ }
116
+ const { problems } = rm.validateManifest(manifest)
117
+ if (problems.length) throw new Error(`release manifest for ${deployment.deploymentId} is invalid:\n${problems.map((p) => ` - ${p}`).join('\n')}`)
118
+ const text = `${JSON.stringify(manifest, null, 2)}\n`
119
+ if (typeof flags.out === 'string') {
120
+ fs.writeFileSync(flags.out, text)
121
+ console.log(`release manifest for ${deployment.deploymentId} @ ${revision.slice(0, 7)} written to ${flags.out}`)
122
+ } else {
123
+ console.log(text)
124
+ }
125
+ if (writer) console.log('next: add permissionsDirectMode.readers (an empty list when no app reads the permissions table directly) and environments.<env>.settings')
126
+ return manifest
127
+ }
128
+
129
+ /**
130
+ * @param {string|undefined} sub
131
+ * @param {object} flags
132
+ */
133
+ async function releaseManifestCommand(sub, flags) {
134
+ if (sub === 'create') return createManifest(flags)
135
+ throw new Error(USAGE)
136
+ }
137
+
138
+ module.exports = { updateFromManifest, releaseManifestCommand }
@@ -0,0 +1,81 @@
1
+ // `saaslayer permissions service-principal roles|assign|unassign`: typed role assignment for service principals (matrix R10)
2
+ // — a declared IAM machine's mapped principal (--machine <principalId> → iam.<principalId>) or any service account id.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { authHeaders } = require('../deployment-api-auth')
6
+
7
+ /**
8
+ * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, machine?: string, role?: string, scope?: string }} ServicePrincipalFlags
9
+ */
10
+
11
+ /**
12
+ * The service principal id from the positional id or --machine, and the permissions API base.
13
+ * @param {string} label @param {string[]} positional @param {ServicePrincipalFlags} flags
14
+ * @returns {{ id: string, apiBase: string }}
15
+ */
16
+ function target(label, positional, flags) {
17
+ const id = flags.machine ? `iam.${flags.machine}` : positional[0]
18
+ if (!id) throw new Error(`${label}: a service principal id or --machine <principalId> is required`)
19
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
20
+ if (!apiBase) throw new Error(`${label}: --api-base (or $SAASLAYER_API_BASE) is required`)
21
+ return { id, apiBase: apiBase.replace(/\/$/, '') }
22
+ }
23
+
24
+ /**
25
+ * Call the typed assignment route; throws with the API's error messages.
26
+ * @param {string} label @param {string} url @param {RequestInit} init
27
+ */
28
+ async function call(label, url, init) {
29
+ const res = await fetch(url, init)
30
+ const body = res.status === 204 ? null : await res.json().catch(() => ({}))
31
+ if (!res.ok) {
32
+ const detail = ((body && body.errors) || []).map((e) => e.message || e.detail).filter(Boolean).join('; ') || JSON.stringify(body)
33
+ throw new Error(`${label} failed (${res.status}): ${detail}`)
34
+ }
35
+ return body
36
+ }
37
+
38
+ /**
39
+ * A service principal's role assignments.
40
+ * @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
41
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
42
+ * @returns {Promise<Array<{ roleId: string, scope: string|null }>>}
43
+ */
44
+ async function servicePrincipalRoles(positional, flags, deps = {}) {
45
+ const { id, apiBase } = target('permissions service-principal roles', positional, flags)
46
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
47
+ const body = await call('permissions service-principal roles', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles`, { method: 'GET', headers: auth })
48
+ return (body.data || []).map((d) => d.attributes)
49
+ }
50
+
51
+ /**
52
+ * Grant a role (--role) to a service principal, deployment-wide unless --scope names an org scope.
53
+ * @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
54
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
55
+ */
56
+ async function servicePrincipalAssign(positional, flags, deps = {}) {
57
+ const { id, apiBase } = target('permissions service-principal assign', positional, flags)
58
+ if (!flags.role) throw new Error('permissions service-principal assign: --role <roleId> is required')
59
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
60
+ const body = await call('permissions service-principal assign', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles`, {
61
+ method: 'POST',
62
+ headers: { ...auth, 'content-type': 'application/json' },
63
+ body: JSON.stringify({ roleId: flags.role, ...(flags.scope ? { scope: flags.scope } : {}) }),
64
+ })
65
+ return body.data.attributes
66
+ }
67
+
68
+ /**
69
+ * Revoke a role (--role, at --scope if given) from a service principal.
70
+ * @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
71
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
72
+ */
73
+ async function servicePrincipalUnassign(positional, flags, deps = {}) {
74
+ const { id, apiBase } = target('permissions service-principal unassign', positional, flags)
75
+ if (!flags.role) throw new Error('permissions service-principal unassign: --role <roleId> is required')
76
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
77
+ const qs = flags.scope ? `?scope=${encodeURIComponent(flags.scope)}` : ''
78
+ await call('permissions service-principal unassign', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles/${encodeURIComponent(flags.role)}${qs}`, { method: 'DELETE', headers: auth })
79
+ }
80
+
81
+ module.exports = { servicePrincipalRoles, servicePrincipalAssign, servicePrincipalUnassign }
@@ -0,0 +1,140 @@
1
+ // `saaslayer settings schema|get|set|diff` — read a module's published settings schema, read a deployment's settings,
2
+ // write a schema-checked patch through PATCH /api/deployments/{id}/settings (then wait for its operation), and compare envs.
3
+ 'use strict'
4
+ const { apiCall } = require('../api-client')
5
+ const { resolveDeployment } = require('../deployments')
6
+ const { finishMutation, requestKeyHeaders } = require('./operations')
7
+ const { parseSetFlags, readSettingsFile, mergePatches, checkPatch, formatSchema, formatSettings, formatChanges, PROTECTED_ENVS } = require('../settings')
8
+ const { readManifest, environmentSettings } = require('../release-manifest')
9
+ const { compareEnvironments, formatComparison } = require('../env-compare')
10
+
11
+ const USAGE = 'usage: saaslayer settings <schema|get|set|diff> … (see saaslayer --help)'
12
+
13
+ /**
14
+ * @param {object} flags
15
+ * @param {string} command for messages
16
+ */
17
+ function oneEnv(flags, command) {
18
+ if (Array.isArray(flags.env)) throw new Error(`${command} takes one --env`)
19
+ return flags
20
+ }
21
+
22
+ /**
23
+ * Resolve the deployment for (project, env, region), print its id under the scope line, and read its settings.
24
+ * @param {object} flags
25
+ * @returns {Promise<{ deployment: Awaited<ReturnType<typeof resolveDeployment>>, settings: import('../settings').DeploymentSettings }>}
26
+ */
27
+ async function readDeploymentSettings(flags) {
28
+ const deployment = await resolveDeployment(flags)
29
+ if (!flags.json) console.error(`deployment: ${deployment.deploymentId} (${deployment.region})`)
30
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, undefined, flags)
31
+ return { deployment, settings: doc.data.attributes }
32
+ }
33
+
34
+ /**
35
+ * @param {string} module
36
+ * @param {string} revision
37
+ * @param {object} flags
38
+ * @returns {Promise<import('../settings').SettingsSchema>}
39
+ */
40
+ async function fetchSchema(module, revision, flags) {
41
+ const doc = await apiCall('GET', `/api/modules/${encodeURIComponent(module)}/settings-schema?revision=${encodeURIComponent(revision)}`, undefined, flags)
42
+ return doc.data.attributes
43
+ }
44
+
45
+ /** `settings schema --module M [--revision SHA]`; without --revision, the revision the selected deployment runs. @param {object} flags */
46
+ async function settingsSchema(flags) {
47
+ const module = flags.module
48
+ if (typeof module !== 'string') throw new Error('settings schema requires --module <module id> (`saaslayer stacks` lists them)')
49
+ let revision = typeof flags.revision === 'string' ? flags.revision : null
50
+ if (!revision) {
51
+ const { deployment, settings } = await readDeploymentSettings(oneEnv(flags, 'settings schema'))
52
+ const deployed = settings.modules.find((m) => m.module === module)
53
+ if (!deployed || !deployed.revision) throw new Error(`${module} is not deployed in ${deployment.deploymentId} — pass --revision <commit sha>`)
54
+ revision = deployed.revision
55
+ }
56
+ const schema = await fetchSchema(module, revision, flags)
57
+ console.log(flags.json ? JSON.stringify(schema, null, 2) : formatSchema(schema).join('\n'))
58
+ return schema
59
+ }
60
+
61
+ /** `settings get --env E`. @param {object} flags */
62
+ async function settingsGet(flags) {
63
+ const { settings } = await readDeploymentSettings(oneEnv(flags, 'settings get'))
64
+ console.log(flags.json ? JSON.stringify(settings, null, 2) : formatSettings(settings).join('\n'))
65
+ return settings
66
+ }
67
+
68
+ /**
69
+ * Check a patch against the deployment's schemas and write it with the settings revision just read. Refusals happen
70
+ * before anything is sent. Waits for the operation unless --no-wait. Shared by `settings set` and `update --param`.
71
+ * @param {import('../settings').SettingsPatch} input
72
+ * @param {object} flags
73
+ */
74
+ async function applySettings(input, flags) {
75
+ const { deployment, settings } = await readDeploymentSettings(flags)
76
+ const schemas = Object.fromEntries(settings.modules.filter((m) => !m.schemaError).map((m) => [m.module, { module: m.module, revision: m.revision, settings: m.settings }]))
77
+ const { patch, billing } = checkPatch(input, schemas, { op: 'update' })
78
+ const reason = typeof flags.reason === 'string' ? flags.reason : undefined
79
+ if (!reason && billing.length) throw new Error(`${billing.join(', ')} changes billing: pass --reason <text>`)
80
+ if (!reason && PROTECTED_ENVS.has(deployment.env)) throw new Error(`${deployment.env} is a protected environment: pass --reason <text>`)
81
+ console.log(`Changing settings of ${deployment.deploymentId} (settings revision ${settings.settingsRevision}):`)
82
+ for (const line of formatChanges(patch, settings)) console.log(line)
83
+ const attributes = { expectedRevision: settings.settingsRevision, settings: patch, ...(reason ? { reason } : {}) }
84
+ let res
85
+ try {
86
+ res = await apiCall('PATCH', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, { data: { type: 'deployment-settings', attributes } }, flags, { headers: requestKeyHeaders() })
87
+ } catch (err) {
88
+ if (err.status === 409) err.message += `\nthe settings changed after they were read (revision ${settings.settingsRevision}): check them with \`saaslayer settings get\` and run the command again`
89
+ throw err
90
+ }
91
+ const written = res.data.attributes
92
+ console.log(`✅ settings revision ${settings.settingsRevision} → ${written.settingsRevision} (operation ${written.operationId})`)
93
+ return finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
94
+ }
95
+
96
+ /** `settings set --env E (--set M.S=V … | --file F) [--reason T]`. @param {object} flags */
97
+ async function settingsSet(flags) {
98
+ const patch = mergePatches(typeof flags.file === 'string' ? readSettingsFile(flags.file) : undefined, parseSetFlags(flags.set, '--set'))
99
+ if (!patch) throw new Error('settings set needs --set <module>.<Setting>=<value> or --file <settings.json>')
100
+ return applySettings(patch, oneEnv(flags, 'settings set'))
101
+ }
102
+
103
+ /**
104
+ * `settings diff --env A --env B [--manifest F]`: module revisions and settings that differ (create-only and secret
105
+ * marked), each side's settings revision, and the gaps between them; with a release manifest, each environment is also
106
+ * checked against the bundle, its permissions writer format and its settings in the manifest.
107
+ * @param {object} flags
108
+ */
109
+ async function settingsDiff(flags) {
110
+ const envs = Array.isArray(flags.env) ? flags.env : []
111
+ if (envs.length !== 2) throw new Error('settings diff needs two --env flags, e.g. --env staging --env prod')
112
+ if (envs[0] === envs[1]) throw new Error('settings diff compares two different environments')
113
+ const manifestFile = typeof flags.manifest === 'string' ? flags.manifest : null
114
+ const manifest = manifestFile ? readManifest(manifestFile) : null
115
+ const envPatches = manifest ? Object.fromEntries(envs.map((env) => [env, environmentSettings(manifest, /** @type {string} */ (manifestFile), env, undefined)])) : {}
116
+ const [a, b] = await Promise.all(envs.map((env) => readDeploymentSettings({ ...flags, env })))
117
+ const comparison = compareEnvironments({ env: envs[0], settings: a.settings }, { env: envs[1], settings: b.settings }, { manifest, envPatches })
118
+ if (flags.json) {
119
+ const side = (s) => ({ deploymentId: s.deployment.deploymentId, settingsRevision: s.settings.settingsRevision })
120
+ console.log(JSON.stringify({ [envs[0]]: side(a), [envs[1]]: side(b), bundleRevision: comparison.bundleRevision, modules: comparison.modules, differences: comparison.settings, gaps: comparison.gaps }, null, 2))
121
+ return comparison
122
+ }
123
+ console.log(`settings revision: ${envs[0]}=${a.settings.settingsRevision} (${a.deployment.deploymentId}) ${envs[1]}=${b.settings.settingsRevision} (${b.deployment.deploymentId})`)
124
+ for (const line of formatComparison(comparison)) console.log(line)
125
+ return comparison
126
+ }
127
+
128
+ /**
129
+ * @param {string|undefined} sub
130
+ * @param {object} flags
131
+ */
132
+ async function settingsCommand(sub, flags) {
133
+ if (sub === 'schema') return settingsSchema(flags)
134
+ if (sub === 'get') return settingsGet(flags)
135
+ if (sub === 'set') return settingsSet(flags)
136
+ if (sub === 'diff') return settingsDiff(flags)
137
+ throw new Error(USAGE)
138
+ }
139
+
140
+ module.exports = { settingsCommand, applySettings, fetchSchema, readDeploymentSettings }
@@ -1,16 +1,21 @@
1
- // `saaslayer stacks` (ctsc.5) — list the vendable stacks a project can deploy (from the BFF catalog).
1
+ // `saaslayer stacks` (ctsc.5) — list the modules a project can deploy (from the BFF catalog, GET /api/stacks):
2
+ // module id, display copy, regions, required modules and the stable outputs SDK discovery relies on.
2
3
  'use strict'
3
- const { apiCall } = require('../api-client')
4
+ const { fetchModuleCatalog } = require('../module-catalog')
4
5
 
5
6
  async function stacks(flags) {
6
- const res = await apiCall('GET', '/api/stacks', undefined, flags)
7
- const rows = res.data || []
8
- console.log('Deployable stacks:')
7
+ const rows = await fetchModuleCatalog(flags)
8
+ console.log('Deployable modules:')
9
9
  for (const r of rows) {
10
10
  const a = r.attributes || {}
11
- console.log(` ${a.service || r.id}${a.description ? ' — ' + a.description : ''}`)
11
+ console.log(` ${r.id}${a.displayName ? ` ${a.displayName}` : ''}${a.description ? ' — ' + a.description : ''}`)
12
+ console.log(` regions: ${a.supportedRegions ? a.supportedRegions.join(', ') : 'any'}`)
13
+ const deps = a.dependencies || []
14
+ if (deps.length) console.log(` requires: ${deps.map((d) => `${d.module} (${d.phase})`).join(', ')}`)
15
+ const stable = (a.outputs || []).filter((o) => o.stability === 'stable').map((o) => o.name)
16
+ if (stable.length) console.log(` outputs: ${stable.join(', ')}`)
12
17
  }
13
- console.log('\nDeploy with: saaslayer deploy --services <a,b>')
18
+ console.log('\nDeploy with: saaslayer deploy --services <module-id,…> [--set <module-id>.<Setting>=<value>]')
14
19
  return rows
15
20
  }
16
21
 
@@ -1,5 +1,5 @@
1
- // `saaslayer users export|import`: move people from another identity system into a SaaSLayer deployment, locally with
2
- // your own credentials (nothing passes through SaaSLayer). Export writes a reviewable manifest; import plans, then applies.
1
+ // `saaslayer users …`: move people from another identity system into a deployment (export a reviewable manifest, import
2
+ // it), and administer its users through user-service /api/users as a deployment login, an IAM principal or an API key.
3
3
  'use strict'
4
4
  const fs = require('fs')
5
5
  const path = require('path')
@@ -8,8 +8,12 @@ const { getProvider } = require('../users-import/providers')
8
8
  const { buildManifest, validateManifest } = require('../users-import/manifest')
9
9
  const { planImport, applyImport, formatPlan } = require('../users-import/import')
10
10
  const { mintSuid } = require('../users-import/ids')
11
- const { authHeaders } = require('../rbac-auth')
11
+ const { authHeaders } = require('../deployment-api-auth')
12
12
  const { exchangeIamToken } = require('../iam-session')
13
+ const creds = require('../credentials')
14
+ const { discoverDeployment, discoverFromFlags } = require('../discovery')
15
+ const { usersApi, readPasswordFromStdin, defaultCreateKey } = require('../users-api')
16
+ const { loadOperations, intervalMs } = require('./operations')
13
17
 
14
18
  /** @param {string} cmd @param {string[]} args */
15
19
  const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
@@ -78,4 +82,188 @@ async function usersImport(flags, deps = {}) {
78
82
  return { plan, report }
79
83
  }
80
84
 
81
- module.exports = { usersExport, usersImport }
85
+ /** The per-user administration subcommands (`saaslayer users <sub>`), in help order. */
86
+ const ADMIN_COMMANDS = ['create', 'get', 'list', 'update', 'disable', 'enable', 'delete', 'reset-password', 'set-password', 'adopt', 'reset-mfa']
87
+
88
+ const USAGE = `usage: saaslayer users <${['export', 'import', ...ADMIN_COMMANDS].join('|')}> … (see saaslayer --help)`
89
+
90
+ /**
91
+ * @typedef {{ stdin?: NodeJS.ReadableStream, log?: (line: string) => void, fetch?: typeof fetch,
92
+ * exchange?: typeof exchangeIamToken, discover?: typeof discoverDeployment, sleep?: (ms: number) => Promise<void> }} AdminDeps
93
+ * @typedef {ReturnType<typeof usersApi>} UsersApi
94
+ */
95
+
96
+ /**
97
+ * The users API a command acts on and how it authenticates. Auth: --iam (IAM principal token), --token (API key), else
98
+ * the selected deployment login (--deployment/--as/--user-service-instance, or the current one) — see deployment-api-auth.js.
99
+ * API bases: --api-base (+ --permissions-api-base for --iam), else the deployment login's own, else (with --iam/--token)
100
+ * discovered from the deployment's public outputs (--deployment <dep_id|env> or --discovery-url).
101
+ * @param {string} command @param {Record<string, any>} flags @param {AdminDeps} deps
102
+ * @returns {Promise<UsersApi>}
103
+ */
104
+ async function usersTarget(command, flags, deps) {
105
+ const exchange = deps.exchange || exchangeIamToken
106
+ let apiBase = flags['api-base'] || process.env.SAASLAYER_USERS_API_BASE
107
+ let permissionsApiBase = flags['permissions-api-base'] || process.env.SAASLAYER_API_BASE
108
+ const machine = Boolean(flags.iam || flags.token)
109
+ if (!apiBase && machine) {
110
+ if (!flags.deployment && !flags['discovery-url']) throw new Error(`users ${command}: --api-base, --deployment or --discovery-url is required with --iam/--token`)
111
+ const { doc } = await discoverFromFlags(flags, { discover: deps.discover })
112
+ apiBase = doc.usersApiBase
113
+ permissionsApiBase = permissionsApiBase || doc.permissionsApiBase
114
+ }
115
+ if (!apiBase) apiBase = creds.selectDeploymentProfile(flags).usersApiBase
116
+ if (flags.iam && !permissionsApiBase) throw new Error(`users ${command}: --permissions-api-base (the permissions API for the IAM exchange, or $SAASLAYER_API_BASE) is required with --iam`)
117
+ /** @type {Promise<Record<string, string>>|null} */
118
+ let headers = null
119
+ const resolveHeaders = () => {
120
+ headers = headers || authHeaders(apiBase, flags, { exchange: (o) => exchange({ ...o, apiBase: permissionsApiBase }) })
121
+ return headers
122
+ }
123
+ return usersApi({ apiBase, headers: resolveHeaders }, { fetch: deps.fetch })
124
+ }
125
+
126
+ /**
127
+ * The password from stdin when --password-stdin is set; a --password flag is refused (shell history, process list).
128
+ * @param {string} command @param {Record<string, any>} flags @param {NodeJS.ReadableStream} stdin
129
+ * @returns {Promise<string|undefined>}
130
+ */
131
+ async function passwordFlag(command, flags, stdin) {
132
+ if (flags.password !== undefined) throw new Error(`users ${command}: pass the password on stdin with --password-stdin (never as a flag)`)
133
+ return flags['password-stdin'] ? readPasswordFromStdin(stdin) : undefined
134
+ }
135
+
136
+ /**
137
+ * The target user: the positional <suid>, --suid, or --email (looked up: users:read).
138
+ * @param {string} command @param {string[]} args @param {Record<string, any>} flags @param {UsersApi} api
139
+ * @returns {Promise<string>}
140
+ */
141
+ async function targetSuid(command, args, flags, api) {
142
+ const suid = args[0] || flags.suid
143
+ if (suid) return String(suid)
144
+ if (flags.email) return api.findSuid(String(flags.email))
145
+ throw new Error(`users ${command}: <suid>, --suid or --email is required`)
146
+ }
147
+
148
+ /** --attr name=value (repeatable) plus --name, as profile attributes. @param {Record<string, any>} flags */
149
+ function profileAttributes(flags) {
150
+ /** @type {Record<string, string>} */
151
+ const attrs = flags.name ? { name: String(flags.name) } : {}
152
+ for (const pair of [].concat(flags.attr || [])) {
153
+ const at = String(pair).indexOf('=')
154
+ if (at < 1) throw new Error(`users update: --attr name=value expected, got ${pair}`)
155
+ attrs[String(pair).slice(0, at)] = String(pair).slice(at + 1)
156
+ }
157
+ if (!Object.keys(attrs).length) throw new Error('users update: --name or --attr name=value is required')
158
+ return attrs
159
+ }
160
+
161
+ /**
162
+ * Create a user (a durable operation). --password-stdin gives a permanent password (password initialization: never
163
+ * prod); --delivery invitation mails a temporary one. Re-running the same command replays the same operation (the
164
+ * default Idempotency-Key is derived from the email). A running operation is waited for; a failed component is an
165
+ * error that says to run the same command again, which resumes it.
166
+ * @param {UsersApi} api @param {string[]} args @param {Record<string, any>} flags @param {Required<Pick<AdminDeps, 'stdin'|'log'>> & AdminDeps} deps
167
+ */
168
+ async function create(api, args, flags, deps) {
169
+ const password = await passwordFlag('create', flags, deps.stdin)
170
+ const attributes = { email: flags.email, password, name: flags.name, soid: flags.soid, suid: flags.suid, delivery: flags.delivery }
171
+ const key = flags['idempotency-key'] || defaultCreateKey(flags.email)
172
+ let result = await api.create(attributes, key)
173
+ const ops = loadOperations()
174
+ if (result.status === 202 && !ops.isTerminal(result.operation.status)) {
175
+ const id = result.operation.id
176
+ const final = await ops.watchOperation({
177
+ id,
178
+ fetchOperation: async () => {
179
+ try {
180
+ return await api.getOperation(id)
181
+ } catch (err) {
182
+ const status = err && /** @type {{ status?: number }} */ (err).status
183
+ if (status && status >= 400 && status < 500 && status !== 408 && status !== 429) Object.assign(err, { fatal: true })
184
+ throw err
185
+ }
186
+ },
187
+ intervalMs: intervalMs(flags),
188
+ sleep: deps.sleep,
189
+ onUpdate: (op) => { if (!ops.isTerminal(op.status)) deps.log(` … operation ${op.id}: ${op.status}`) },
190
+ resumeCommand: 'run the same command again',
191
+ })
192
+ result = final.status === 'succeeded' ? await api.create(attributes, key) : { ...result, operation: final }
193
+ }
194
+ if (result.status === 202) {
195
+ const op = result.operation
196
+ throw new Error([`users create: operation ${op.id} is ${op.status}; run the same command again to resume it`, ...ops.formatOperation(op).slice(1)].join('\n'))
197
+ }
198
+ return { result, output: { suid: result.user && result.user.id, ...(result.user ? result.user.attributes : {}), operation: result.operation.id } }
199
+ }
200
+
201
+ /**
202
+ * Adopt an account made outside SaaSLayer's routes (users:adopt) and, with --password-stdin, give it a permanent
203
+ * password (users:set-password). Both need EnablePasswordInitialization.
204
+ * @param {UsersApi} api @param {string[]} args @param {Record<string, any>} flags @param {Required<Pick<AdminDeps, 'stdin'|'log'>> & AdminDeps} deps
205
+ */
206
+ async function adopt(api, args, flags, deps) {
207
+ const password = await passwordFlag('adopt', flags, deps.stdin)
208
+ const suid = await targetSuid('adopt', args, flags, api)
209
+ const adopted = await api.adopt(suid)
210
+ if (password) await api.setPassword(suid, password)
211
+ return { suid, adopted: Boolean(adopted.adopted), passwordSet: Boolean(password) }
212
+ }
213
+
214
+ /**
215
+ * The per-user subcommands: (api, args, flags, deps) → what is printed.
216
+ * @type {Record<string, (api: UsersApi, args: string[], flags: Record<string, any>, deps: Required<Pick<AdminDeps, 'stdin'|'log'>> & AdminDeps) => Promise<any>>}
217
+ */
218
+ const HANDLERS = {
219
+ create,
220
+ get: async (api, args, flags) => api.get(await targetSuid('get', args, flags, api), { org: flags.org }),
221
+ list: async (api, args, flags) => {
222
+ if (!flags.email && !flags['default-org']) throw new Error('users list: --email or --default-org is required')
223
+ return api.list({ email: flags.email, defaultOrg: flags['default-org'] }, { limit: flags.limit, cursor: flags.cursor })
224
+ },
225
+ update: async (api, args, flags) => {
226
+ const attributes = profileAttributes(flags)
227
+ return api.update(await targetSuid('update', args, flags, api), attributes)
228
+ },
229
+ disable: async (api, args, flags) => api.disable(await targetSuid('disable', args, flags, api)),
230
+ enable: async (api, args, flags) => api.enable(await targetSuid('enable', args, flags, api)),
231
+ delete: async (api, args, flags) => {
232
+ const suid = args[0] || flags.suid
233
+ if (!suid) throw new Error('users delete: <suid> or --suid is required (--email only helps find a user that was never projected)')
234
+ if (!flags.yes) throw new Error(`users delete: deletes ${suid} everywhere (sign-in, passwordless data, profile) and cannot be undone — pass --yes`)
235
+ return api.remove(String(suid), { email: flags.email })
236
+ },
237
+ 'reset-password': async (api, args, flags) => api.resetPassword(await targetSuid('reset-password', args, flags, api)),
238
+ 'set-password': async (api, args, flags, deps) => {
239
+ const password = await passwordFlag('set-password', flags, deps.stdin)
240
+ if (!password) throw new Error('users set-password: --password-stdin is required (pipe the password)')
241
+ return api.setPassword(await targetSuid('set-password', args, flags, api), password, { permanent: !flags.temporary })
242
+ },
243
+ adopt,
244
+ 'reset-mfa': async (api, args, flags) => {
245
+ const reason = typeof flags.reason === 'string' ? flags.reason.trim() : ''
246
+ if (!reason) throw new Error('users reset-mfa: --reason is required (recorded in the audit line)')
247
+ return api.resetMfa(await targetSuid('reset-mfa', args, flags, api), reason)
248
+ },
249
+ }
250
+
251
+ /**
252
+ * `saaslayer users <sub>` for one deployment's users through user-service /api/users: prints the result as JSON
253
+ * (secret-named fields redacted) and returns it.
254
+ * @param {string} sub @param {string[]} args positional arguments after the subcommand
255
+ * @param {Record<string, any>} flags @param {AdminDeps} [deps]
256
+ */
257
+ async function usersAdmin(sub, args, flags, deps = {}) {
258
+ const handler = HANDLERS[sub]
259
+ if (!handler) throw new Error(USAGE)
260
+ const full = { ...deps, stdin: deps.stdin || process.stdin, log: deps.log || console.log }
261
+ if (sub === 'create' && !flags.email) throw new Error('users create: --email is required')
262
+ const api = await usersTarget(sub, flags, full)
263
+ const out = await handler(api, args, flags, full)
264
+ const { result, output } = sub === 'create' ? out : { result: out, output: out }
265
+ full.log(JSON.stringify(loadOperations().redact(output), null, 2))
266
+ return result
267
+ }
268
+
269
+ module.exports = { usersExport, usersImport, usersAdmin, ADMIN_COMMANDS, USAGE }
package/src/config.js CHANGED
@@ -2,6 +2,19 @@
2
2
  // control-plane GET /config endpoint; falls back to flags / env for local + pre-endpoint use.
3
3
  'use strict'
4
4
 
5
+ const DEFAULT_CONTROL_PLANE_URL = 'https://api.saaslayer.com'
6
+
7
+ /**
8
+ * The control-plane API base: --config-url, then $SAASLAYER_CONFIG_URL, else the hosted control plane.
9
+ * @param {Record<string, any>} [flags]
10
+ * @returns {{ value: string, source: 'flag' | 'env' | 'default' }}
11
+ */
12
+ function controlPlaneUrl(flags = {}) {
13
+ if (flags['config-url']) return { value: flags['config-url'], source: 'flag' }
14
+ if (process.env.SAASLAYER_CONFIG_URL) return { value: process.env.SAASLAYER_CONFIG_URL, source: 'env' }
15
+ return { value: DEFAULT_CONTROL_PLANE_URL, source: 'default' }
16
+ }
17
+
5
18
  // Decode a JWT payload (middle segment) without verifying — used only to read our own id token's
6
19
  // claims (sub, email) after Cognito issued it. Never trust this for authorization.
7
20
  function decodeJwt(token) {
@@ -11,10 +24,13 @@ function decodeJwt(token) {
11
24
  return JSON.parse(json)
12
25
  }
13
26
 
27
+ // Pool coordinates: an explicit --config-url/$SAASLAYER_CONFIG_URL wins, then explicit pool flags/env, then the
28
+ // default control plane's /api/config.
14
29
  async function resolvePoolConfig(flags = {}) {
15
- const configUrl = flags['config-url'] || process.env.SAASLAYER_CONFIG_URL
16
- if (configUrl) {
17
- const url = `${String(configUrl).replace(/\/$/, '')}/api/config`
30
+ const cp = controlPlaneUrl(flags)
31
+ const explicitPool = (flags['user-pool-id'] || process.env.SAASLAYER_USER_POOL_ID) && (flags['client-id'] || process.env.SAASLAYER_USER_POOL_CLIENT_ID)
32
+ if (cp.source !== 'default' || !explicitPool) {
33
+ const url = `${String(cp.value).replace(/\/$/, '')}/api/config`
18
34
  const res = await fetch(url)
19
35
  if (!res.ok) throw new Error(`GET ${url} failed (${res.status})`)
20
36
  const cfg = await res.json()
@@ -27,10 +43,7 @@ async function resolvePoolConfig(flags = {}) {
27
43
  const region = flags.region || process.env.SAASLAYER_USER_POOL_REGION || process.env.AWS_REGION || 'us-east-1'
28
44
  const userPoolId = flags['user-pool-id'] || process.env.SAASLAYER_USER_POOL_ID
29
45
  const clientId = flags['client-id'] || process.env.SAASLAYER_USER_POOL_CLIENT_ID
30
- if (!userPoolId || !clientId) {
31
- throw new Error('user pool not configured: pass --config-url (control-plane), or set SAASLAYER_USER_POOL_ID + SAASLAYER_USER_POOL_CLIENT_ID (or --user-pool-id/--client-id)')
32
- }
33
46
  return { region, userPoolId, clientId }
34
47
  }
35
48
 
36
- module.exports = { resolvePoolConfig, decodeJwt }
49
+ module.exports = { resolvePoolConfig, decodeJwt, controlPlaneUrl, DEFAULT_CONTROL_PLANE_URL }