saaslayer 0.0.2 → 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.
- package/README.md +195 -8
- package/bin/saaslayer.js +454 -38
- package/package.json +19 -4
- package/src/api-client.js +91 -0
- package/src/aws-sigv4.js +47 -0
- package/src/commands/access-admins.js +73 -0
- package/src/commands/accounts.js +54 -0
- package/src/commands/activity.js +33 -0
- package/src/commands/aws.js +132 -0
- package/src/commands/catalog.js +246 -0
- package/src/commands/context.js +64 -0
- package/src/commands/deploy.js +118 -0
- package/src/commands/first-admin.js +42 -0
- package/src/commands/foundation.js +405 -0
- package/src/commands/lifecycle.js +124 -0
- package/src/commands/login.js +261 -0
- package/src/commands/machine-trust.js +96 -0
- package/src/commands/migrate.js +290 -0
- package/src/commands/operations.js +140 -0
- package/src/commands/orgs.js +81 -0
- package/src/commands/permissions-inspect.js +228 -0
- package/src/commands/release-manifest.js +138 -0
- package/src/commands/service-principals.js +81 -0
- package/src/commands/settings.js +140 -0
- package/src/commands/stacks.js +22 -0
- package/src/commands/users.js +269 -0
- package/src/config.js +49 -0
- package/src/context-store.js +37 -0
- package/src/credentials.js +285 -0
- package/src/deployment-api-auth.js +61 -0
- package/src/deployment-auth.js +38 -0
- package/src/deployments.js +26 -0
- package/src/discovery.js +66 -0
- package/src/env-compare.js +143 -0
- package/src/foundation-template.js +57 -0
- package/src/iam-session.js +67 -0
- package/src/migrations-lib.js +15 -0
- package/src/module-catalog.js +66 -0
- package/src/permissions-request.js +43 -0
- package/src/prompt.js +19 -0
- package/src/release-manifest.js +334 -0
- package/src/scope.js +114 -0
- package/src/settings.js +272 -0
- package/src/users-api.js +165 -0
- package/src/users-import/ids.js +24 -0
- package/src/users-import/import.js +292 -0
- package/src/users-import/manifest.js +90 -0
- package/src/users-import/providers/cognito.js +61 -0
- package/src/users-import/providers/index.js +24 -0
- package/templates/saaslayer-foundation-region.yml +109 -0
- package/templates/{host-account.yml → saaslayer-foundation.yml} +381 -87
|
@@ -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 }
|
|
@@ -0,0 +1,22 @@
|
|
|
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.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { fetchModuleCatalog } = require('../module-catalog')
|
|
5
|
+
|
|
6
|
+
async function stacks(flags) {
|
|
7
|
+
const rows = await fetchModuleCatalog(flags)
|
|
8
|
+
console.log('Deployable modules:')
|
|
9
|
+
for (const r of rows) {
|
|
10
|
+
const a = r.attributes || {}
|
|
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(', ')}`)
|
|
17
|
+
}
|
|
18
|
+
console.log('\nDeploy with: saaslayer deploy --services <module-id,…> [--set <module-id>.<Setting>=<value>]')
|
|
19
|
+
return rows
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
module.exports = { stacks }
|
|
@@ -0,0 +1,269 @@
|
|
|
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
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
const { execFileSync } = require('child_process')
|
|
7
|
+
const { getProvider } = require('../users-import/providers')
|
|
8
|
+
const { buildManifest, validateManifest } = require('../users-import/manifest')
|
|
9
|
+
const { planImport, applyImport, formatPlan } = require('../users-import/import')
|
|
10
|
+
const { mintSuid } = require('../users-import/ids')
|
|
11
|
+
const { authHeaders } = require('../deployment-api-auth')
|
|
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')
|
|
17
|
+
|
|
18
|
+
/** @param {string} cmd @param {string[]} args */
|
|
19
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
|
|
20
|
+
|
|
21
|
+
/** kebab-case flag names → camelCase provider options */
|
|
22
|
+
const camel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase())
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {Record<string, any>} flags --provider, --out, the provider's own flags, and --role-map <module.js>
|
|
26
|
+
* @param {{ exec?: typeof defaultExec, log?: (line: string) => void, now?: () => Date }} [deps]
|
|
27
|
+
*/
|
|
28
|
+
async function usersExport(flags, deps = {}) {
|
|
29
|
+
const { exec = defaultExec, log = console.log, now = () => new Date() } = deps
|
|
30
|
+
if (!flags.provider) throw new Error('users export: --provider is required (e.g. cognito)')
|
|
31
|
+
if (!flags.out) throw new Error('users export: --out is required (where to write the manifest)')
|
|
32
|
+
const provider = getProvider(flags.provider)
|
|
33
|
+
const opts = Object.fromEntries(Object.keys(provider.options).filter((k) => flags[k] !== undefined).map((k) => [camel(k), flags[k]]))
|
|
34
|
+
const roleFor = flags['role-map'] ? require(path.resolve(flags['role-map'])) : undefined
|
|
35
|
+
const source = { ...(opts.userPoolId ? { userPoolId: opts.userPoolId } : {}), ...(opts.region ? { region: opts.region } : {}) }
|
|
36
|
+
const manifest = await buildManifest({ provider: provider.name, source, users: provider.export(opts, { exec }), roleFor, now: now() })
|
|
37
|
+
const errors = validateManifest(manifest)
|
|
38
|
+
fs.writeFileSync(path.resolve(flags.out), JSON.stringify(manifest, null, 2) + '\n', { mode: 0o600 })
|
|
39
|
+
const users = manifest.accounts.reduce((n, a) => n + a.users.length, 0)
|
|
40
|
+
log(`exported ${users} users in ${manifest.accounts.length} accounts to ${flags.out}`)
|
|
41
|
+
log('The manifest holds personal data (emails, names, phones). Keep it private and delete it after the import.')
|
|
42
|
+
if (errors.length) log(`fix before importing:\n ${errors.join('\n ')}`)
|
|
43
|
+
return manifest
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Dry run by default (prints the plan); --apply imports and writes a report next to the manifest (or --report).
|
|
48
|
+
* @param {Record<string, any>} flags
|
|
49
|
+
* @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]
|
|
51
|
+
*/
|
|
52
|
+
async function usersImport(flags, deps = {}) {
|
|
53
|
+
const { exec = defaultExec, log = console.log, now = () => new Date() } = deps
|
|
54
|
+
if (!flags.manifest) throw new Error('users import: --manifest is required (from users export)')
|
|
55
|
+
const manifest = JSON.parse(fs.readFileSync(path.resolve(flags.manifest), 'utf8'))
|
|
56
|
+
const errors = validateManifest(manifest)
|
|
57
|
+
if (errors.length) throw new Error(`users import: the manifest is invalid:\n ${errors.join('\n ')}`)
|
|
58
|
+
const target = {
|
|
59
|
+
userPoolId: flags['user-pool-id'],
|
|
60
|
+
region: flags.region || process.env.AWS_REGION,
|
|
61
|
+
profile: flags.profile,
|
|
62
|
+
apiBase: flags['api-base'] || process.env.SAASLAYER_API_BASE,
|
|
63
|
+
product: flags.product,
|
|
64
|
+
logsRoleArn: flags['logs-role-arn'],
|
|
65
|
+
}
|
|
66
|
+
const plan = await planImport(manifest, target, { exec })
|
|
67
|
+
log(formatPlan(plan, { apply: Boolean(flags.apply) }))
|
|
68
|
+
if (!flags.apply) return { plan }
|
|
69
|
+
const report = await applyImport(plan, target, {
|
|
70
|
+
exec,
|
|
71
|
+
fetch: deps.fetch || fetch,
|
|
72
|
+
mint: deps.mint || mintSuid,
|
|
73
|
+
sleep: deps.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
74
|
+
authHeaders: deps.authHeaders || (() => authHeaders(target.apiBase, flags, { exchange: exchangeIamToken })),
|
|
75
|
+
now,
|
|
76
|
+
})
|
|
77
|
+
const reportPath = path.resolve(flags.report || flags.manifest.replace(/\.json$/, '') + '.import-report.json')
|
|
78
|
+
fs.writeFileSync(reportPath, JSON.stringify(report, null, 2) + '\n', { mode: 0o600 })
|
|
79
|
+
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' : ''}`)
|
|
82
|
+
return { plan, report }
|
|
83
|
+
}
|
|
84
|
+
|
|
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
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Resolves the SaaSLayer control-plane Cognito pool coordinates the CLI logs in against. Prefers the
|
|
2
|
+
// control-plane GET /config endpoint; falls back to flags / env for local + pre-endpoint use.
|
|
3
|
+
'use strict'
|
|
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
|
+
|
|
18
|
+
// Decode a JWT payload (middle segment) without verifying — used only to read our own id token's
|
|
19
|
+
// claims (sub, email) after Cognito issued it. Never trust this for authorization.
|
|
20
|
+
function decodeJwt(token) {
|
|
21
|
+
const seg = String(token || '').split('.')[1]
|
|
22
|
+
if (!seg) throw new Error('malformed token')
|
|
23
|
+
const json = Buffer.from(seg.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')
|
|
24
|
+
return JSON.parse(json)
|
|
25
|
+
}
|
|
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.
|
|
29
|
+
async function resolvePoolConfig(flags = {}) {
|
|
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`
|
|
34
|
+
const res = await fetch(url)
|
|
35
|
+
if (!res.ok) throw new Error(`GET ${url} failed (${res.status})`)
|
|
36
|
+
const cfg = await res.json()
|
|
37
|
+
const userPoolId = cfg.userPoolId || cfg.UserPoolId
|
|
38
|
+
const clientId = cfg.clientId || cfg.UserPoolClientId
|
|
39
|
+
const region = cfg.region || 'us-east-1'
|
|
40
|
+
if (!userPoolId || !clientId) throw new Error('/config did not return userPoolId + clientId')
|
|
41
|
+
return { region, userPoolId, clientId, mechanisms: cfg.mechanisms }
|
|
42
|
+
}
|
|
43
|
+
const region = flags.region || process.env.SAASLAYER_USER_POOL_REGION || process.env.AWS_REGION || 'us-east-1'
|
|
44
|
+
const userPoolId = flags['user-pool-id'] || process.env.SAASLAYER_USER_POOL_ID
|
|
45
|
+
const clientId = flags['client-id'] || process.env.SAASLAYER_USER_POOL_CLIENT_ID
|
|
46
|
+
return { region, userPoolId, clientId }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = { resolvePoolConfig, decodeJwt, controlPlaneUrl, DEFAULT_CONTROL_PLANE_URL }
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Local CLI context: the active org (and later project) so commands don't need --org every time.
|
|
2
|
+
// Stored in ~/.saaslayer/context.json (separate from credentials.json). Best-effort, never throws.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const os = require('os')
|
|
6
|
+
const path = require('path')
|
|
7
|
+
|
|
8
|
+
function dir() {
|
|
9
|
+
return process.env.SAASLAYER_HOME || path.join(os.homedir(), '.saaslayer')
|
|
10
|
+
}
|
|
11
|
+
function file() {
|
|
12
|
+
return path.join(dir(), 'context.json')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function load() {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(fs.readFileSync(file(), 'utf8')) || {}
|
|
18
|
+
} catch {
|
|
19
|
+
return {}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function save(ctx) {
|
|
24
|
+
fs.mkdirSync(dir(), { recursive: true })
|
|
25
|
+
fs.writeFileSync(file(), JSON.stringify(ctx, null, 2), { mode: 0o600 })
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function get(key) {
|
|
29
|
+
return load()[key] || null
|
|
30
|
+
}
|
|
31
|
+
function set(key, value) {
|
|
32
|
+
const ctx = load()
|
|
33
|
+
ctx[key] = value
|
|
34
|
+
save(ctx)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
module.exports = { get, set, load, save, file }
|