saaslayer 0.0.1 → 0.0.7
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 +53 -3
- package/bin/saaslayer.js +226 -41
- package/package.json +20 -3
- package/src/api-client.js +71 -0
- package/src/aws-sigv4.js +47 -0
- package/src/commands/accounts.js +25 -0
- package/src/commands/aws.js +132 -0
- package/src/commands/catalog.js +245 -0
- package/src/commands/deploy.js +49 -0
- package/src/commands/iam-principals.js +53 -0
- package/src/commands/lifecycle.js +91 -0
- package/src/commands/login.js +87 -0
- package/src/commands/migrate.js +290 -0
- package/src/commands/orgs.js +56 -0
- package/src/commands/rbac-inspect.js +228 -0
- package/src/commands/stacks.js +17 -0
- package/src/commands/users.js +81 -0
- package/src/config.js +36 -0
- package/src/context-store.js +37 -0
- package/src/credentials.js +98 -0
- package/src/deployments.js +27 -0
- package/src/foundation-template.js +57 -0
- package/src/iam-session.js +93 -0
- package/src/migrations-lib.js +15 -0
- package/src/prompt.js +19 -0
- package/src/rbac-auth.js +25 -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} +359 -82
- package/vendor/ids/index.d.ts +21 -0
- package/vendor/ids/index.js +237 -0
|
@@ -0,0 +1,81 @@
|
|
|
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.
|
|
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('../rbac-auth')
|
|
12
|
+
const { exchangeIamToken } = require('../iam-session')
|
|
13
|
+
|
|
14
|
+
/** @param {string} cmd @param {string[]} args */
|
|
15
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
|
|
16
|
+
|
|
17
|
+
/** kebab-case flag names → camelCase provider options */
|
|
18
|
+
const camel = (s) => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase())
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {Record<string, any>} flags --provider, --out, the provider's own flags, and --role-map <module.js>
|
|
22
|
+
* @param {{ exec?: typeof defaultExec, log?: (line: string) => void, now?: () => Date }} [deps]
|
|
23
|
+
*/
|
|
24
|
+
async function usersExport(flags, deps = {}) {
|
|
25
|
+
const { exec = defaultExec, log = console.log, now = () => new Date() } = deps
|
|
26
|
+
if (!flags.provider) throw new Error('users export: --provider is required (e.g. cognito)')
|
|
27
|
+
if (!flags.out) throw new Error('users export: --out is required (where to write the manifest)')
|
|
28
|
+
const provider = getProvider(flags.provider)
|
|
29
|
+
const opts = Object.fromEntries(Object.keys(provider.options).filter((k) => flags[k] !== undefined).map((k) => [camel(k), flags[k]]))
|
|
30
|
+
const roleFor = flags['role-map'] ? require(path.resolve(flags['role-map'])) : undefined
|
|
31
|
+
const source = { ...(opts.userPoolId ? { userPoolId: opts.userPoolId } : {}), ...(opts.region ? { region: opts.region } : {}) }
|
|
32
|
+
const manifest = await buildManifest({ provider: provider.name, source, users: provider.export(opts, { exec }), roleFor, now: now() })
|
|
33
|
+
const errors = validateManifest(manifest)
|
|
34
|
+
fs.writeFileSync(path.resolve(flags.out), JSON.stringify(manifest, null, 2) + '\n', { mode: 0o600 })
|
|
35
|
+
const users = manifest.accounts.reduce((n, a) => n + a.users.length, 0)
|
|
36
|
+
log(`exported ${users} users in ${manifest.accounts.length} accounts to ${flags.out}`)
|
|
37
|
+
log('The manifest holds personal data (emails, names, phones). Keep it private and delete it after the import.')
|
|
38
|
+
if (errors.length) log(`fix before importing:\n ${errors.join('\n ')}`)
|
|
39
|
+
return manifest
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Dry run by default (prints the plan); --apply imports and writes a report next to the manifest (or --report).
|
|
44
|
+
* @param {Record<string, any>} flags
|
|
45
|
+
* @param {{ exec?: typeof defaultExec, fetch?: typeof fetch, log?: (line: string) => void, now?: () => Date,
|
|
46
|
+
* mint?: () => string, sleep?: (ms: number) => Promise<void>, authHeaders?: () => Promise<Record<string, string>> }} [deps]
|
|
47
|
+
*/
|
|
48
|
+
async function usersImport(flags, deps = {}) {
|
|
49
|
+
const { exec = defaultExec, log = console.log, now = () => new Date() } = deps
|
|
50
|
+
if (!flags.manifest) throw new Error('users import: --manifest is required (from users export)')
|
|
51
|
+
const manifest = JSON.parse(fs.readFileSync(path.resolve(flags.manifest), 'utf8'))
|
|
52
|
+
const errors = validateManifest(manifest)
|
|
53
|
+
if (errors.length) throw new Error(`users import: the manifest is invalid:\n ${errors.join('\n ')}`)
|
|
54
|
+
const target = {
|
|
55
|
+
userPoolId: flags['user-pool-id'],
|
|
56
|
+
region: flags.region || process.env.AWS_REGION,
|
|
57
|
+
profile: flags.profile,
|
|
58
|
+
apiBase: flags['api-base'] || process.env.SAASLAYER_API_BASE,
|
|
59
|
+
product: flags.product,
|
|
60
|
+
logsRoleArn: flags['logs-role-arn'],
|
|
61
|
+
}
|
|
62
|
+
const plan = await planImport(manifest, target, { exec })
|
|
63
|
+
log(formatPlan(plan, { apply: Boolean(flags.apply) }))
|
|
64
|
+
if (!flags.apply) return { plan }
|
|
65
|
+
const report = await applyImport(plan, target, {
|
|
66
|
+
exec,
|
|
67
|
+
fetch: deps.fetch || fetch,
|
|
68
|
+
mint: deps.mint || mintSuid,
|
|
69
|
+
sleep: deps.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
70
|
+
authHeaders: deps.authHeaders || (() => authHeaders(target.apiBase, flags, { exchange: exchangeIamToken })),
|
|
71
|
+
now,
|
|
72
|
+
})
|
|
73
|
+
const reportPath = path.resolve(flags.report || flags.manifest.replace(/\.json$/, '') + '.import-report.json')
|
|
74
|
+
fs.writeFileSync(reportPath, JSON.stringify(report, null, 2) + '\n', { mode: 0o600 })
|
|
75
|
+
const s = report.summary
|
|
76
|
+
log(`imported: ${s.created} created, ${s.linked} linked, ${s.failed} failed, ${s.skipped} skipped; ${s.orgsCreated} orgs created, ${s.ownersGranted} owners granted`)
|
|
77
|
+
log(`report: ${reportPath}${s.failed ? ' — re-run to retry the failed users' : ''}`)
|
|
78
|
+
return { plan, report }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = { usersExport, usersImport }
|
package/src/config.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
// Decode a JWT payload (middle segment) without verifying — used only to read our own id token's
|
|
6
|
+
// claims (sub, email) after Cognito issued it. Never trust this for authorization.
|
|
7
|
+
function decodeJwt(token) {
|
|
8
|
+
const seg = String(token || '').split('.')[1]
|
|
9
|
+
if (!seg) throw new Error('malformed token')
|
|
10
|
+
const json = Buffer.from(seg.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')
|
|
11
|
+
return JSON.parse(json)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
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`
|
|
18
|
+
const res = await fetch(url)
|
|
19
|
+
if (!res.ok) throw new Error(`GET ${url} failed (${res.status})`)
|
|
20
|
+
const cfg = await res.json()
|
|
21
|
+
const userPoolId = cfg.userPoolId || cfg.UserPoolId
|
|
22
|
+
const clientId = cfg.clientId || cfg.UserPoolClientId
|
|
23
|
+
const region = cfg.region || 'us-east-1'
|
|
24
|
+
if (!userPoolId || !clientId) throw new Error('/config did not return userPoolId + clientId')
|
|
25
|
+
return { region, userPoolId, clientId, mechanisms: cfg.mechanisms }
|
|
26
|
+
}
|
|
27
|
+
const region = flags.region || process.env.SAASLAYER_USER_POOL_REGION || process.env.AWS_REGION || 'us-east-1'
|
|
28
|
+
const userPoolId = flags['user-pool-id'] || process.env.SAASLAYER_USER_POOL_ID
|
|
29
|
+
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
|
+
return { region, userPoolId, clientId }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { resolvePoolConfig, decodeJwt }
|
|
@@ -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 }
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Local credential store for the saaslayer CLI. Persists Cognito tokens per SaaSLayer account under
|
|
2
|
+
// ~/.saaslayer/credentials.json (0600), keyed by userId, with a `current` pointer for the active one.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const os = require('os')
|
|
6
|
+
const path = require('path')
|
|
7
|
+
|
|
8
|
+
// The store dir is overridable (SAASLAYER_HOME) so CI and tests never touch a real home directory.
|
|
9
|
+
function storeDir() {
|
|
10
|
+
return process.env.SAASLAYER_HOME || path.join(os.homedir(), '.saaslayer')
|
|
11
|
+
}
|
|
12
|
+
function storePath() {
|
|
13
|
+
return path.join(storeDir(), 'credentials.json')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Read the store; a missing or unreadable/corrupt file yields an empty store (never throws).
|
|
17
|
+
function load() {
|
|
18
|
+
try {
|
|
19
|
+
const raw = fs.readFileSync(storePath(), 'utf8')
|
|
20
|
+
const parsed = JSON.parse(raw)
|
|
21
|
+
if (!parsed || typeof parsed !== 'object') return { users: {}, current: null }
|
|
22
|
+
return { users: parsed.users || {}, current: parsed.current || null }
|
|
23
|
+
} catch (err) {
|
|
24
|
+
return { users: {}, current: null }
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Write the store atomically with 0600 perms so tokens are not world-readable.
|
|
29
|
+
function save(store) {
|
|
30
|
+
const dir = storeDir()
|
|
31
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
32
|
+
const tmp = path.join(dir, `.credentials.${process.pid}.tmp`)
|
|
33
|
+
const body = JSON.stringify({ users: store.users || {}, current: store.current || null }, null, 2)
|
|
34
|
+
fs.writeFileSync(tmp, body, { mode: 0o600 })
|
|
35
|
+
fs.renameSync(tmp, storePath())
|
|
36
|
+
try { fs.chmodSync(storePath(), 0o600) } catch (err) { /* best-effort on platforms without chmod */ }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Upsert an account and make it current. `record` carries { userId, email, env, idToken, accessToken,
|
|
40
|
+
// refreshToken, expiresAt }. Stamps lastUsedAt so `list` can order most-recently-used first.
|
|
41
|
+
function setUser(record) {
|
|
42
|
+
if (!record || !record.userId) throw new Error('setUser requires a userId')
|
|
43
|
+
const store = load()
|
|
44
|
+
store.users[record.userId] = { ...store.users[record.userId], ...record, lastUsedAt: Date.now() }
|
|
45
|
+
store.current = record.userId
|
|
46
|
+
save(store)
|
|
47
|
+
return store.users[record.userId]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function getCurrent() {
|
|
51
|
+
const store = load()
|
|
52
|
+
if (!store.current) return null
|
|
53
|
+
return store.users[store.current] || null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Resolve a selector to a stored userId: an exact userId match wins, else a case-insensitive email match.
|
|
57
|
+
// Throws if nothing matches, or if an email matches more than one account (disambiguate with the userId).
|
|
58
|
+
function resolve(selector) {
|
|
59
|
+
if (!selector) throw new Error('an account selector (email or userId) is required')
|
|
60
|
+
const store = load()
|
|
61
|
+
if (store.users[selector]) return selector
|
|
62
|
+
const needle = String(selector).toLowerCase()
|
|
63
|
+
const matches = Object.values(store.users).filter((u) => (u.email || '').toLowerCase() === needle)
|
|
64
|
+
if (matches.length === 1) return matches[0].userId
|
|
65
|
+
if (matches.length > 1) throw new Error(`"${selector}" matches ${matches.length} accounts — switch by userId: ${matches.map((m) => m.userId).join(', ')}`)
|
|
66
|
+
throw new Error(`no stored account for "${selector}"`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Switch the active account. Accepts an email or a userId; bumps lastUsedAt so the switched-to account
|
|
70
|
+
// is the most-recently-used.
|
|
71
|
+
function setCurrent(selector) {
|
|
72
|
+
const userId = resolve(selector)
|
|
73
|
+
const store = load()
|
|
74
|
+
store.users[userId] = { ...store.users[userId], lastUsedAt: Date.now() }
|
|
75
|
+
store.current = userId
|
|
76
|
+
save(store)
|
|
77
|
+
return store.users[userId]
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// All cached accounts, most-recently-used first (accounts without a lastUsedAt sort last).
|
|
81
|
+
function list() {
|
|
82
|
+
const store = load()
|
|
83
|
+
return Object.values(store.users).sort((a, b) => (b.lastUsedAt || 0) - (a.lastUsedAt || 0))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Remove one account (or the current one) and clear/repoint `current` as needed.
|
|
87
|
+
function clear(userId) {
|
|
88
|
+
const store = load()
|
|
89
|
+
const target = userId || store.current
|
|
90
|
+
if (target && store.users[target]) delete store.users[target]
|
|
91
|
+
if (store.current === target) {
|
|
92
|
+
const remaining = Object.keys(store.users)
|
|
93
|
+
store.current = remaining.length ? remaining[0] : null
|
|
94
|
+
}
|
|
95
|
+
save(store)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
module.exports = { storeDir, storePath, load, save, setUser, getCurrent, resolve, setCurrent, list, clear }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Shared deploy helpers: the active project, and resolving a deployment id for (project, env, region)
|
|
2
|
+
// from the project-deployments view (so lifecycle commands take project+env+region, not a raw id).
|
|
3
|
+
'use strict'
|
|
4
|
+
const { apiCall } = require('./api-client')
|
|
5
|
+
const context = require('./context-store')
|
|
6
|
+
|
|
7
|
+
function activeProject(flags) {
|
|
8
|
+
const p = flags.project || context.get('project')
|
|
9
|
+
if (!p) throw new Error('no project selected — run `saaslayer project use <id>` or pass --project')
|
|
10
|
+
return p
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function resolveDeployment(flags) {
|
|
14
|
+
const project = activeProject(flags)
|
|
15
|
+
const env = flags.env || 'prod'
|
|
16
|
+
const region = flags.region
|
|
17
|
+
const view = await apiCall('GET', `/api/projects/${encodeURIComponent(project)}/deployments`, undefined, flags)
|
|
18
|
+
const group = (view.environments || []).find((g) => g.environment === env)
|
|
19
|
+
let instances = group ? group.instances : []
|
|
20
|
+
if (region) instances = instances.filter((i) => i.region === region)
|
|
21
|
+
if (instances.length === 0) throw new Error(`no ${env} deployment${region ? ` in ${region}` : ''} for project ${project}`)
|
|
22
|
+
if (instances.length > 1) throw new Error(`multiple ${env} deployments — pass --region <r>: ${instances.map((i) => i.region).join(', ')}`)
|
|
23
|
+
const inst = instances[0]
|
|
24
|
+
return { project, env, region: inst.region, deploymentId: inst.deploymentId, status: inst.status }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
module.exports = { activeProject, resolveDeployment }
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Deployable copy of the foundation template: whole-line comments stripped so it fits CloudFormation's
|
|
2
|
+
// 51,200-byte inline template limit (the documented source is larger), plus redaction for deploy argv in errors.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const os = require('os')
|
|
6
|
+
const path = require('path')
|
|
7
|
+
|
|
8
|
+
/** CloudFormation rejects inline (non-S3) templates larger than this many bytes. */
|
|
9
|
+
const CFN_INLINE_TEMPLATE_LIMIT = 51200
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Removes whole-line YAML comments. The template keeps `#` only at line start for comments; content lines
|
|
13
|
+
* (folded Description text, URLs with fragments) are left untouched.
|
|
14
|
+
* @param {string} text
|
|
15
|
+
* @returns {string}
|
|
16
|
+
*/
|
|
17
|
+
function stripComments(text) {
|
|
18
|
+
return text.split('\n').filter((line) => !/^\s*#/.test(line)).join('\n')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Writes the stripped template to a temp file and returns its path, for `aws cloudformation deploy --template-file`.
|
|
23
|
+
* @param {string} templatePath
|
|
24
|
+
* @returns {string}
|
|
25
|
+
*/
|
|
26
|
+
function writeDeployableTemplate(templatePath) {
|
|
27
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'saaslayer-foundation-'))
|
|
28
|
+
const file = path.join(dir, path.basename(templatePath))
|
|
29
|
+
fs.writeFileSync(file, stripComments(fs.readFileSync(templatePath, 'utf8')))
|
|
30
|
+
return file
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Deploy argv with the ExternalId override masked, for error messages and logs.
|
|
35
|
+
* @param {string[]} args
|
|
36
|
+
* @returns {string[]}
|
|
37
|
+
*/
|
|
38
|
+
function redactArgs(args) {
|
|
39
|
+
return args.map((a) => (a.startsWith('ExternalId=') ? 'ExternalId=****' : a))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `aws cloudformation deploy` argv for `saaslayer init`, deploying the stripped template copy. A re-run that
|
|
44
|
+
* changes nothing is a clean no-op.
|
|
45
|
+
* @param {{ template: string, stackName: string, region: string, controlPlaneAccount: string, externalId: string, stackPrefix: string, orgId: string }} o
|
|
46
|
+
* @returns {string[]}
|
|
47
|
+
*/
|
|
48
|
+
function initDeployArgs(o) {
|
|
49
|
+
return [
|
|
50
|
+
'cloudformation', 'deploy', '--template-file', writeDeployableTemplate(o.template), '--stack-name', o.stackName, '--region', o.region,
|
|
51
|
+
'--capabilities', 'CAPABILITY_NAMED_IAM', '--no-fail-on-empty-changeset',
|
|
52
|
+
'--parameter-overrides',
|
|
53
|
+
`ControlPlaneAccountId=${o.controlPlaneAccount}`, `ExternalId=${o.externalId}`, `StackNamePrefix=${o.stackPrefix}`, `OrgId=${o.orgId}`,
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = { CFN_INLINE_TEMPLATE_LIMIT, stripComments, writeDeployableTemplate, redactArgs, initDeployArgs }
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Customer IAM principals for a cloud-prem SaaSLayer deployment: the SSM path that declares them, a light file check,
|
|
2
|
+
// and the exchange of a signed STS GetCallerIdentity proof (your AWS credentials) for an rbac iam_ token.
|
|
3
|
+
'use strict'
|
|
4
|
+
const crypto = require('crypto')
|
|
5
|
+
const { execFileSync } = require('child_process')
|
|
6
|
+
const { signRequest } = require('./aws-sigv4')
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* SSM parameter (in the customer's own account) holding the deployment's IAM principals.
|
|
10
|
+
* @param {string} deploymentId
|
|
11
|
+
* @param {string} [serviceInstance] rbac service instance ('_' = default)
|
|
12
|
+
*/
|
|
13
|
+
function iamPrincipalsParam(deploymentId, serviceInstance = '_') {
|
|
14
|
+
if (!deploymentId) throw new Error('a deployment id is required')
|
|
15
|
+
return `/saaslayer/deployment/${deploymentId}/${serviceInstance}/rbac/iam-principals`
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Shape check before writing; rbac-service does the full validation and ignores an invalid config.
|
|
20
|
+
* @param {{ principals?: Array<{ principalId?: string, roleArn?: string, scopes?: string[] }> }} file
|
|
21
|
+
* @returns {string[]}
|
|
22
|
+
*/
|
|
23
|
+
function validatePrincipalsFile(file) {
|
|
24
|
+
if (!file || !Array.isArray(file.principals)) return ['file must be { "principals": [...] }']
|
|
25
|
+
const errors = []
|
|
26
|
+
file.principals.forEach((p, i) => {
|
|
27
|
+
if (!p.principalId) errors.push(`principals[${i}]: principalId is required`)
|
|
28
|
+
if (!/^arn:aws[a-z-]*:iam::\d{12}:(role|user)\//.test(p.roleArn || '')) errors.push(`principals[${i}]: roleArn must be an IAM role or user ARN`)
|
|
29
|
+
if (!Array.isArray(p.scopes) || !p.scopes.length) errors.push(`principals[${i}]: at least one scope is required`)
|
|
30
|
+
})
|
|
31
|
+
return errors
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Your current AWS credentials (env, profile, SSO) via the AWS CLI.
|
|
36
|
+
* @param {{ profile?: string }} [opts]
|
|
37
|
+
* @returns {{ accessKeyId: string, secretAccessKey: string, sessionToken?: string }}
|
|
38
|
+
*/
|
|
39
|
+
function awsCredentials({ profile } = {}) {
|
|
40
|
+
const args = ['configure', 'export-credentials', '--format', 'process', ...(profile ? ['--profile', profile] : [])]
|
|
41
|
+
const c = JSON.parse(execFileSync('aws', args, { encoding: 'utf8' }))
|
|
42
|
+
return { accessKeyId: c.AccessKeyId, secretAccessKey: c.SecretAccessKey, sessionToken: c.SessionToken }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Signed STS GetCallerIdentity request binding the proof to `principalId` (and a one-time nonce).
|
|
47
|
+
* @param {{ principalId: string, region: string, credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date, nonce?: string }} opts
|
|
48
|
+
*/
|
|
49
|
+
function buildStsEnvelope({ principalId, region, credentials, now = new Date(), nonce = crypto.randomUUID() }) {
|
|
50
|
+
const host = `sts.${region}.amazonaws.com`
|
|
51
|
+
const url = `https://${host}/`
|
|
52
|
+
const body = 'Action=GetCallerIdentity&Version=2011-06-15'
|
|
53
|
+
const { headers } = signRequest({
|
|
54
|
+
method: 'POST',
|
|
55
|
+
url,
|
|
56
|
+
body,
|
|
57
|
+
region,
|
|
58
|
+
service: 'sts',
|
|
59
|
+
credentials,
|
|
60
|
+
now,
|
|
61
|
+
headers: {
|
|
62
|
+
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
|
|
63
|
+
Host: host,
|
|
64
|
+
'X-Saaslayer-Principal-Type': 'SERVICE_ACCOUNT',
|
|
65
|
+
'X-Saaslayer-Principal-Id': principalId,
|
|
66
|
+
'X-Saaslayer-Nonce': nonce,
|
|
67
|
+
'X-Saaslayer-Timestamp': now.toISOString().replace(/\.\d{3}/, ''),
|
|
68
|
+
},
|
|
69
|
+
})
|
|
70
|
+
return { method: 'POST', url, headers, body }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Exchange your AWS identity for an iam_ token on the deployment's rbac API.
|
|
75
|
+
* @param {{ apiBase: string, principalId: string, region: string, credentials?: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, profile?: string }} opts
|
|
76
|
+
* @returns {Promise<string>}
|
|
77
|
+
*/
|
|
78
|
+
async function exchangeIamToken({ apiBase, principalId, region, credentials, profile }) {
|
|
79
|
+
const envelope = buildStsEnvelope({ principalId, region, credentials: credentials || awsCredentials({ profile }) })
|
|
80
|
+
const res = await fetch(`${apiBase.replace(/\/$/, '')}/auth/aws-iam`, {
|
|
81
|
+
method: 'POST',
|
|
82
|
+
headers: { 'content-type': 'application/json' },
|
|
83
|
+
body: JSON.stringify({ principalId, envelope }),
|
|
84
|
+
})
|
|
85
|
+
const body = await res.json().catch(() => ({}))
|
|
86
|
+
if (!res.ok) {
|
|
87
|
+
const detail = (body.errors || []).map((e) => e.message).filter(Boolean).join('; ') || JSON.stringify(body)
|
|
88
|
+
throw new Error(`IAM exchange failed (${res.status}): ${detail}`)
|
|
89
|
+
}
|
|
90
|
+
return body.data.attributes.token
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = { iamPrincipalsParam, validatePrincipalsFile, awsCredentials, buildStsEnvelope, exchangeIamToken }
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// The per-service migration runner (@saaslayer/migrations, unpublished) that `saaslayer migrate` drives. Monorepo
|
|
2
|
+
// source first (vendor/ is a prepack snapshot that goes stale in a checkout); the published CLI carries vendor/migrations.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
|
|
7
|
+
// Resolved at runtime because it is never shipped: present only in a monorepo checkout.
|
|
8
|
+
const MONOREPO_MIGRATIONS = path.join(__dirname, '../../migrations/src')
|
|
9
|
+
const VENDORED = path.join(__dirname, '../vendor/migrations')
|
|
10
|
+
|
|
11
|
+
function loadMigrations() {
|
|
12
|
+
return require(fs.existsSync(path.join(MONOREPO_MIGRATIONS, 'index.js')) ? MONOREPO_MIGRATIONS : VENDORED)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = { loadMigrations }
|
package/src/prompt.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Minimal interactive prompts for the CLI (confirm y/N + free text). readline-based; used by the deploy
|
|
2
|
+
// cost-confirm and the destroy typed-name confirmation. Non-interactive stdin resolves to '' (caller decides).
|
|
3
|
+
'use strict'
|
|
4
|
+
const readline = require('readline')
|
|
5
|
+
|
|
6
|
+
function ask(question) {
|
|
7
|
+
return new Promise((resolve) => {
|
|
8
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY })
|
|
9
|
+
rl.question(question, (answer) => { rl.close(); resolve(String(answer || '').trim()) })
|
|
10
|
+
})
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// y/N confirm — returns true only on an explicit yes.
|
|
14
|
+
async function confirm(question) {
|
|
15
|
+
const a = (await ask(`${question} [y/N] `)).toLowerCase()
|
|
16
|
+
return a === 'y' || a === 'yes'
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
module.exports = { ask, confirm }
|
package/src/rbac-auth.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Auth headers for calls to a deployment's rbac API from the CLI: an IAM principal token (--iam, exchanged from your
|
|
2
|
+
// AWS identity) or an API key (--token). Shared by the catalog and users commands.
|
|
3
|
+
'use strict'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Request auth headers: an IAM principal token (--iam, exchanged from your AWS identity) as a bearer only, or a
|
|
7
|
+
* --token sent as both api key and bearer.
|
|
8
|
+
* @param {string} apiBase
|
|
9
|
+
* @param {{ token?: string, iam?: string, region?: string, profile?: string }} flags
|
|
10
|
+
* @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> }} deps
|
|
11
|
+
* @returns {Promise<Record<string, string>>}
|
|
12
|
+
*/
|
|
13
|
+
async function authHeaders(apiBase, flags, { exchange }) {
|
|
14
|
+
if (flags.iam) {
|
|
15
|
+
const region = flags.region || process.env.AWS_REGION || 'us-west-2'
|
|
16
|
+
const token = await exchange({ apiBase, principalId: flags.iam, region, profile: flags.profile })
|
|
17
|
+
return { authorization: `Bearer ${token}` }
|
|
18
|
+
}
|
|
19
|
+
const token = flags.token || process.env.SAASLAYER_TOKEN
|
|
20
|
+
if (!token) throw new Error('--iam <principalId> or --token (or $SAASLAYER_TOKEN) is required')
|
|
21
|
+
return { 'x-api-key': token, authorization: `Bearer ${token}` }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
module.exports = { authHeaders }
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The platform user-id minter (@saaslayer/ids' bare 26-char UUIDv7 TypeID suffix) for imported users' custom:suid —
|
|
2
|
+
// the same generator the user-service uses. Vendored into the published CLI; the monorepo source is the fallback.
|
|
3
|
+
'use strict'
|
|
4
|
+
const path = require('path')
|
|
5
|
+
|
|
6
|
+
// The monorepo source, for running the CLI from a checkout before vendor/ is synced. Resolved at runtime because it
|
|
7
|
+
// is never shipped: the published package carries vendor/ids (synced on prepack).
|
|
8
|
+
const MONOREPO_IDS = path.join(__dirname, '../../../ids/src')
|
|
9
|
+
|
|
10
|
+
function loadIds() {
|
|
11
|
+
try {
|
|
12
|
+
return require('../../vendor/ids')
|
|
13
|
+
} catch (err) {
|
|
14
|
+
if (err && err.code !== 'MODULE_NOT_FOUND') throw err
|
|
15
|
+
return require(MONOREPO_IDS)
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @returns {string} a new stable SaaSLayer user id */
|
|
20
|
+
function mintSuid() {
|
|
21
|
+
return loadIds().generateTypeIdSuffix()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { mintSuid }
|