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,132 @@
|
|
|
1
|
+
// `saaslayer aws connect` — connect the caller's own AWS account (cloud-prem) to an org. Mints a
|
|
2
|
+
// per-host-account trust secret via the control-plane API, deploys the SaaSLayer foundation stack into
|
|
3
|
+
// that account using the operator's AMBIENT AWS creds, then verifies the cross-account trust.
|
|
4
|
+
'use strict'
|
|
5
|
+
const fs = require('fs')
|
|
6
|
+
const os = require('os')
|
|
7
|
+
const path = require('path')
|
|
8
|
+
const crypto = require('crypto')
|
|
9
|
+
const { execFileSync } = require('child_process')
|
|
10
|
+
const context = require('../context-store')
|
|
11
|
+
const { apiCall } = require('../api-client')
|
|
12
|
+
|
|
13
|
+
// CloudFormation's inline template limit is 51,200 bytes. The foundation template exceeds it with its
|
|
14
|
+
// comments (~40% of the file), so `aws cloudformation deploy --template-file` would demand --s3-bucket.
|
|
15
|
+
// Strip full-line comments + blank lines into a temp file for the deploy — the SOURCE keeps every comment.
|
|
16
|
+
// Safe: the foundation template has no inline `#` inside quoted values (only full-line comments).
|
|
17
|
+
function strippedTemplate(templateFile) {
|
|
18
|
+
const out = fs.readFileSync(templateFile, 'utf8')
|
|
19
|
+
.split('\n')
|
|
20
|
+
.filter((l) => { const t = l.trim(); return t !== '' && !t.startsWith('#') })
|
|
21
|
+
.join('\n')
|
|
22
|
+
const tmp = path.join(os.tmpdir(), `saaslayer-foundation-${process.pid}.yml`)
|
|
23
|
+
fs.writeFileSync(tmp, out)
|
|
24
|
+
return tmp
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Absolute path to the bundled foundation template. This template file is the SHARED contract between
|
|
28
|
+
// `saaslayer aws connect` (customer BYO, ambient creds) and cplane account-vending (assumed-role creds) —
|
|
29
|
+
// see control-plane/cli/src/accounts/foundation.ts, which deploys this same template + param contract.
|
|
30
|
+
const FOUNDATION_TEMPLATE = path.join(__dirname, '..', '..', 'templates', 'saaslayer-foundation.yml')
|
|
31
|
+
|
|
32
|
+
// Build the `aws cloudformation deploy` argv for the foundation stack. Pure — unit-testable, and shared
|
|
33
|
+
// so the stack name + param contract live in one place.
|
|
34
|
+
function foundationDeployArgs({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId = '', templateFile = FOUNDATION_TEMPLATE }) {
|
|
35
|
+
return [
|
|
36
|
+
'cloudformation', 'deploy',
|
|
37
|
+
'--template-file', templateFile,
|
|
38
|
+
'--stack-name', 'saaslayer-foundation',
|
|
39
|
+
'--region', region,
|
|
40
|
+
'--capabilities', 'CAPABILITY_NAMED_IAM',
|
|
41
|
+
'--parameter-overrides',
|
|
42
|
+
`ControlPlaneAccountId=${controlPlaneAccount}`,
|
|
43
|
+
`ExternalId=${externalId}`,
|
|
44
|
+
`StackNamePrefix=${stackNamePrefix}`,
|
|
45
|
+
`OrgId=${orgId}`,
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Deploy the bundled foundation template into the target account. `env` lets a caller inject ASSUMED
|
|
50
|
+
// role creds (AWS_ACCESS_KEY_ID/SECRET/SESSION_TOKEN); omit to use the caller's ambient creds.
|
|
51
|
+
function deployFoundation({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId, env }) {
|
|
52
|
+
const templateFile = strippedTemplate(FOUNDATION_TEMPLATE)
|
|
53
|
+
execFileSync('aws', foundationDeployArgs({ controlPlaneAccount, externalId, region, stackNamePrefix, orgId, templateFile }),
|
|
54
|
+
{ stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// The account-global saaslayer-foundation stack holds IAM only (a role can't be created twice, so it's
|
|
58
|
+
// account-scoped). Region-bound resources — first the shared deployment-artifact bucket — live in a SEPARATE
|
|
59
|
+
// per-region stack, so a fully-deployable account needs BOTH. `aws connect` deploys both.
|
|
60
|
+
const FOUNDATION_REGION_TEMPLATE = path.join(__dirname, '..', '..', 'templates', 'saaslayer-foundation-region.yml')
|
|
61
|
+
|
|
62
|
+
// The per-region stack name: `saaslayer-foundation-<region>`. The region in the name IS the scope signal
|
|
63
|
+
// (`saaslayer-foundation` = account-global; `saaslayer-foundation-<region>` = that region).
|
|
64
|
+
function foundationRegionStackName(region) {
|
|
65
|
+
return `saaslayer-foundation-${region}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Derive the shared artifact bucket name. MUST mirror the deployer's derivation byte-for-byte so the bucket this
|
|
69
|
+
// creates == the SERVERLESS_DEPLOYMENT_BUCKET the deployer injects. Source of truth (kept in sync, conformance-
|
|
70
|
+
// tested): control-plane/services/deployer-service/src/refs.ts opaqueAccountToken/artifactsBucketName, and
|
|
71
|
+
// @saaslayer/config. The published CLI can't take those (unpublished) workspace deps, so it inlines the algorithm.
|
|
72
|
+
function opaqueAccountToken(accountId, purpose) {
|
|
73
|
+
const acct = String(accountId == null ? '' : accountId).trim()
|
|
74
|
+
const p = String(purpose == null ? '' : purpose).trim()
|
|
75
|
+
if (!acct) throw new Error('opaqueAccountToken: accountId is required')
|
|
76
|
+
if (!p) throw new Error('opaqueAccountToken: purpose is required')
|
|
77
|
+
return crypto.createHash('sha256').update(`${acct}|${p}`).digest('hex').slice(0, 20)
|
|
78
|
+
}
|
|
79
|
+
function artifactsBucketName(accountId, region) {
|
|
80
|
+
return `sl-artifacts-${region}-${opaqueAccountToken(accountId, 'artifacts').slice(0, 12)}`
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Build the `aws cloudformation deploy` argv for the per-region foundation stack. Pure — unit-testable.
|
|
84
|
+
// No IAM in this stack, so no CAPABILITY_NAMED_IAM; a no-op re-deploy must be clean, not a failure.
|
|
85
|
+
function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templateFile = FOUNDATION_REGION_TEMPLATE }) {
|
|
86
|
+
return [
|
|
87
|
+
'cloudformation', 'deploy',
|
|
88
|
+
'--template-file', templateFile,
|
|
89
|
+
'--stack-name', foundationRegionStackName(region),
|
|
90
|
+
'--region', region,
|
|
91
|
+
'--no-fail-on-empty-changeset',
|
|
92
|
+
'--parameter-overrides',
|
|
93
|
+
`ArtifactsBucketName=${bucket}`,
|
|
94
|
+
]
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Deploy the per-region foundation stack (shared artifact bucket) with the caller's creds (or injected `env`).
|
|
98
|
+
function deployFoundationRegion({ accountId, region, env }) {
|
|
99
|
+
const bucket = artifactsBucketName(accountId, region)
|
|
100
|
+
execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket }),
|
|
101
|
+
{ stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
|
|
102
|
+
return bucket
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function awsConnect(flags) {
|
|
106
|
+
const accountId = flags['aws-account']
|
|
107
|
+
const region = flags.region || 'us-east-1'
|
|
108
|
+
const orgId = flags.org || context.get('org')
|
|
109
|
+
if (!accountId) throw new Error('aws connect requires --aws-account <12-digit id>')
|
|
110
|
+
if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
|
|
111
|
+
// D5: bind the account to the active project by default; --org-wide opens it to all org projects.
|
|
112
|
+
const orgWide = flags['org-wide'] === true || flags['org-wide'] === 'true'
|
|
113
|
+
const projectId = orgWide ? undefined : flags.project || context.get('project')
|
|
114
|
+
|
|
115
|
+
const scope = orgWide ? 'all projects in the org' : projectId ? `project ${projectId}` : 'all projects in the org (no active project)'
|
|
116
|
+
console.log(`Connecting AWS account ${accountId} (${region}) to org ${orgId} — deployable by ${scope}…`)
|
|
117
|
+
const conn = await apiCall('POST', '/api/aws/connect', { accountId, region, orgId, projectId, orgWide }, flags)
|
|
118
|
+
console.log(` registered (trust secret minted); deploying the account-global foundation stack into ${accountId} with your AWS creds…`)
|
|
119
|
+
deployFoundation({ controlPlaneAccount: conn.controlPlaneAccountId, externalId: conn.externalId, region, stackNamePrefix: conn.stackNamePrefix, orgId })
|
|
120
|
+
console.log(` global foundation deployed; deploying the per-region foundation (shared artifact bucket) into ${region}…`)
|
|
121
|
+
const bucket = deployFoundationRegion({ accountId, region })
|
|
122
|
+
console.log(` per-region foundation deployed (bucket ${bucket}); verifying cross-account trust…`)
|
|
123
|
+
const v = await apiCall('POST', '/api/aws/connect/verify', { accountId, region }, flags)
|
|
124
|
+
console.log(`✅ AWS account ${accountId} connected to org ${orgId} (${v.bootstrapStatus})`)
|
|
125
|
+
return v
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
module.exports = {
|
|
129
|
+
awsConnect, deployFoundation, foundationDeployArgs, FOUNDATION_TEMPLATE,
|
|
130
|
+
deployFoundationRegion, foundationRegionDeployArgs, foundationRegionStackName, artifactsBucketName,
|
|
131
|
+
FOUNDATION_REGION_TEMPLATE,
|
|
132
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// `saaslayer catalog apply|get|export` and `saaslayer rbac register`: apply a product's role catalog (PUT
|
|
2
|
+
// /catalog/:product), register a service under its product, and export the published registry snapshot.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
const { exchangeIamToken } = require('../iam-session')
|
|
7
|
+
const { authHeaders } = require('../rbac-auth')
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {{ type: 'string' | 'number' | 'boolean' | 'string[]' | 'principalRef' | 'ip', required: boolean, nullable?: boolean, pii?: boolean }} AttributeSchema
|
|
11
|
+
* @typedef {{ product: string, catalogVersion: number,
|
|
12
|
+
* resources: Record<string, { actions: string[], attributes?: Record<string, AttributeSchema> }>,
|
|
13
|
+
* trustedContext?: boolean, contextSchema?: Record<string, AttributeSchema>,
|
|
14
|
+
* roles: object[], delegation?: object, selfCheck?: object[] }} CatalogManifest
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The API's error messages, each prefixed with its JSON:API source pointer when it has one.
|
|
19
|
+
* @param {{ errors?: Array<{ message?: string, detail?: string, source?: { pointer?: string } }> }} body
|
|
20
|
+
* @returns {string}
|
|
21
|
+
*/
|
|
22
|
+
function apiErrorDetail(body) {
|
|
23
|
+
return (body.errors || [])
|
|
24
|
+
.map((e) => {
|
|
25
|
+
const text = e.message || e.detail
|
|
26
|
+
return text && e.source && e.source.pointer ? `${e.source.pointer}: ${text}` : text
|
|
27
|
+
})
|
|
28
|
+
.filter(Boolean).join('; ') || JSON.stringify(body)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Human-readable summary of an apply/dry-run result.
|
|
33
|
+
* @param {{ product: string, catalogVersion: number, plan: string, dryRun?: boolean,
|
|
34
|
+
* diff: { added: string[], removed: string[], unchanged: string[], changed: Array<{ id: string, fields: string[], permissionsAdded: string[], permissionsRemoved: string[], conditionsChanged?: Array<{ permission: string, before: object|null, after: object|null }> }>, attributes?: string[] },
|
|
35
|
+
* warnings?: string[],
|
|
36
|
+
* assignmentCounts?: Record<string, number>, adopted?: Array<{ id: string, orgId: string, assignments: number }>, selfCheck?: Array<{ ok: boolean }>,
|
|
37
|
+
* registry?: { version: number, published: boolean, stalenessSeconds: number } | null }} a
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
function formatApplyResult(a) {
|
|
41
|
+
const lines = [`${a.product} catalog v${a.catalogVersion} — plan: ${a.plan}${a.dryRun ? ' (dry run, nothing written)' : ''}`]
|
|
42
|
+
for (const id of a.diff.added) lines.push(` + ${id}`)
|
|
43
|
+
for (const c of a.diff.changed) {
|
|
44
|
+
// A permission whose only change is its condition prints as one `when before -> after` line
|
|
45
|
+
const conditions = c.conditionsChanged || []
|
|
46
|
+
const conditional = new Set(conditions.map((x) => x.permission))
|
|
47
|
+
const unconditioned = (/** @type {string} */ p) => !conditional.has(p.split(' when ')[0])
|
|
48
|
+
const parts = [
|
|
49
|
+
c.fields.length ? `fields: ${c.fields.join(', ')}` : '',
|
|
50
|
+
...c.permissionsAdded.filter(unconditioned).map((p) => `+${p}`),
|
|
51
|
+
...c.permissionsRemoved.filter(unconditioned).map((p) => `-${p}`),
|
|
52
|
+
].filter(Boolean)
|
|
53
|
+
if (parts.length) lines.push(` ~ ${c.id} ${parts.join(' ')}`)
|
|
54
|
+
const when = (/** @type {object|null} */ w) => (w ? JSON.stringify(w) : 'none')
|
|
55
|
+
for (const x of conditions) lines.push(` ~ ${c.id} ${x.permission} when ${when(x.before)} -> ${when(x.after)}`)
|
|
56
|
+
}
|
|
57
|
+
for (const id of a.diff.removed) lines.push(` - ${id} (${(a.assignmentCounts || {})[id] || 0} assignments)`)
|
|
58
|
+
for (const id of a.diff.unchanged) lines.push(` = ${id}`)
|
|
59
|
+
for (const r of a.adopted || []) lines.push(` ^ ${r.id} adopted from org ${r.orgId} (${r.assignments} assignments kept)`)
|
|
60
|
+
for (const line of a.diff.attributes || []) lines.push(` ${line}`)
|
|
61
|
+
const probes = a.selfCheck || []
|
|
62
|
+
lines.push(`selfCheck: ${probes.filter((p) => p.ok).length}/${probes.length} probes pass`)
|
|
63
|
+
for (const w of a.warnings || []) lines.push(`warn: ${w}`)
|
|
64
|
+
const staleness = registryLine(a.registry)
|
|
65
|
+
if (staleness) lines.push(staleness)
|
|
66
|
+
return lines.join('\n')
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The registry publish line: which snapshot version went live and how stale a container may be.
|
|
71
|
+
* @param {{ version: number, published: boolean, stalenessSeconds: number } | null | undefined} registry
|
|
72
|
+
* @returns {string|null}
|
|
73
|
+
*/
|
|
74
|
+
function registryLine(registry) {
|
|
75
|
+
if (!registry) return null
|
|
76
|
+
return registry.published
|
|
77
|
+
? `registry v${registry.version} published — live in every container within ${registry.stalenessSeconds} s`
|
|
78
|
+
: `registry v${registry.version} unchanged`
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @param {string[]} positional [manifestPath]
|
|
83
|
+
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, 'dry-run'?: boolean, 'allow-orphan'?: boolean, adopt?: boolean }} flags
|
|
84
|
+
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
85
|
+
* @returns {Promise<string>} the printed summary
|
|
86
|
+
*/
|
|
87
|
+
async function catalogApply(positional, flags, deps = {}) {
|
|
88
|
+
const manifestPath = positional[0]
|
|
89
|
+
if (!manifestPath) throw new Error('catalog apply: a manifest path is required')
|
|
90
|
+
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
91
|
+
if (!apiBase) throw new Error('catalog apply: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
92
|
+
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
93
|
+
/** @type {CatalogManifest} */
|
|
94
|
+
const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
|
|
95
|
+
const query = new URLSearchParams()
|
|
96
|
+
if (flags['dry-run']) query.set('dryRun', 'true')
|
|
97
|
+
if (flags['allow-orphan']) query.set('allowOrphan', 'true')
|
|
98
|
+
if (flags.adopt) query.set('adopt', 'true')
|
|
99
|
+
const qs = query.toString()
|
|
100
|
+
const url = `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(manifest.product)}${qs ? `?${qs}` : ''}`
|
|
101
|
+
const res = await fetch(url, {
|
|
102
|
+
method: 'PUT',
|
|
103
|
+
headers: { ...auth, 'content-type': 'application/json' },
|
|
104
|
+
body: JSON.stringify(manifest),
|
|
105
|
+
})
|
|
106
|
+
const body = await res.json().catch(() => ({}))
|
|
107
|
+
if (!res.ok) {
|
|
108
|
+
throw new Error(`catalog apply failed (${res.status}): ${apiErrorDetail(body)}`)
|
|
109
|
+
}
|
|
110
|
+
const a = body.data.attributes
|
|
111
|
+
const summary = formatApplyResult(a)
|
|
112
|
+
console.log(summary)
|
|
113
|
+
if (a.plan === 'apply' && !a.dryRun && a.verified !== true) throw new Error('catalog apply: roles were written but not verified on read-back')
|
|
114
|
+
return summary
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Call a catalog route and return its attributes; throws with the API's error messages.
|
|
119
|
+
* @param {string} label @param {string} url @param {RequestInit} init
|
|
120
|
+
*/
|
|
121
|
+
async function callCatalog(label, url, init) {
|
|
122
|
+
const res = await fetch(url, init)
|
|
123
|
+
const body = await res.json().catch(() => ({}))
|
|
124
|
+
if (!res.ok) {
|
|
125
|
+
throw new Error(`${label} failed (${res.status}): ${apiErrorDetail(body)}`)
|
|
126
|
+
}
|
|
127
|
+
return body.data.attributes
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Make a member the first owner of an org (only while it has none). Needs an IAM principal with owners:bootstrap.
|
|
132
|
+
* @param {string[]} positional [product]
|
|
133
|
+
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, org?: string, user?: string }} flags
|
|
134
|
+
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
135
|
+
*/
|
|
136
|
+
async function catalogBootstrapOwner(positional, flags, deps = {}) {
|
|
137
|
+
const product = positional[0]
|
|
138
|
+
if (!product) throw new Error('catalog bootstrap-owner: a product is required')
|
|
139
|
+
if (!flags.org || !flags.user) throw new Error('catalog bootstrap-owner: --org and --user are required')
|
|
140
|
+
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
141
|
+
if (!apiBase) throw new Error('catalog bootstrap-owner: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
142
|
+
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
143
|
+
return callCatalog('catalog bootstrap-owner', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/bootstrap-owner`, {
|
|
144
|
+
method: 'POST',
|
|
145
|
+
headers: { ...auth, 'content-type': 'application/json' },
|
|
146
|
+
body: JSON.stringify({ orgId: flags.org, userId: flags.user }),
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Compare every org's owner counter with a live recount; --apply repairs mismatches.
|
|
152
|
+
* @param {string[]} positional [product]
|
|
153
|
+
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, apply?: boolean, org?: string }} flags
|
|
154
|
+
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
155
|
+
*/
|
|
156
|
+
async function catalogReconcileOwners(positional, flags, deps = {}) {
|
|
157
|
+
const product = positional[0]
|
|
158
|
+
if (!product) throw new Error('catalog reconcile-owners: a product is required')
|
|
159
|
+
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
160
|
+
if (!apiBase) throw new Error('catalog reconcile-owners: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
161
|
+
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
162
|
+
const query = new URLSearchParams()
|
|
163
|
+
if (flags.apply) query.set('apply', 'true')
|
|
164
|
+
if (flags.org) query.set('orgId', flags.org)
|
|
165
|
+
const qs = query.toString()
|
|
166
|
+
return callCatalog('catalog reconcile-owners', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/reconcile-owners${qs ? `?${qs}` : ''}`, {
|
|
167
|
+
method: 'POST',
|
|
168
|
+
headers: { ...auth, 'content-type': 'application/json' },
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The catalog currently applied for a product (GET /catalog/:product).
|
|
174
|
+
* @param {string[]} positional [product]
|
|
175
|
+
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string }} flags
|
|
176
|
+
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
177
|
+
* @returns {Promise<{ product: string, catalogVersion: number, contentHash: string, roleIds: string[], manifest: object }>}
|
|
178
|
+
*/
|
|
179
|
+
async function catalogGet(positional, flags, deps = {}) {
|
|
180
|
+
const product = positional[0]
|
|
181
|
+
if (!product) throw new Error('catalog get: a product is required')
|
|
182
|
+
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
183
|
+
if (!apiBase) throw new Error('catalog get: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
184
|
+
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
185
|
+
const res = await fetch(`${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}`, { method: 'GET', headers: auth })
|
|
186
|
+
const body = await res.json().catch(() => ({}))
|
|
187
|
+
if (!res.ok) {
|
|
188
|
+
const detail = (body.errors || []).map((e) => e.message || e.detail).filter(Boolean).join('; ') || JSON.stringify(body)
|
|
189
|
+
throw new Error(`catalog get failed (${res.status}): ${detail}`)
|
|
190
|
+
}
|
|
191
|
+
return body.data.attributes
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Register (upsert) a service's rbac.manifest.json under its product (POST /catalog/register). A service belongs to
|
|
196
|
+
* exactly one product: --product (or the manifest's `product`) is required.
|
|
197
|
+
* @param {string[]} positional [manifestPath]
|
|
198
|
+
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, product?: string }} flags
|
|
199
|
+
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
200
|
+
* @returns {Promise<string>} the printed summary
|
|
201
|
+
*/
|
|
202
|
+
async function rbacRegister(positional, flags, deps = {}) {
|
|
203
|
+
const manifestPath = positional[0]
|
|
204
|
+
if (!manifestPath) throw new Error('rbac register: a manifest path is required')
|
|
205
|
+
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
206
|
+
if (!apiBase) throw new Error('rbac register: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
207
|
+
const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
|
|
208
|
+
const product = flags.product || manifest.product
|
|
209
|
+
if (!product) throw new Error('rbac register: --product is required (the product that owns this service)')
|
|
210
|
+
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
211
|
+
const a = await callCatalog('register', `${apiBase.replace(/\/$/, '')}/catalog/register`, {
|
|
212
|
+
method: 'POST',
|
|
213
|
+
headers: { ...auth, 'content-type': 'application/json' },
|
|
214
|
+
body: JSON.stringify({ ...manifest, product }),
|
|
215
|
+
})
|
|
216
|
+
const lines = [`registered "${a.service || manifest.service}" under product "${a.product || product}" (${a.resourceCount ?? '?'} resource types)`]
|
|
217
|
+
const staleness = registryLine(a.registry)
|
|
218
|
+
if (staleness) lines.push(staleness)
|
|
219
|
+
const summary = lines.join('\n')
|
|
220
|
+
console.log(summary)
|
|
221
|
+
return summary
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Write the currently published registry snapshot ({ meta, snapshot }) to a file — the pinned registry rbac-node
|
|
226
|
+
* direct mode loads (GET /catalog/registry/snapshot).
|
|
227
|
+
* @param {string[]} positional unused
|
|
228
|
+
* @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, snapshot?: boolean, out?: string }} flags
|
|
229
|
+
* @param {{ exchange?: typeof exchangeIamToken }} [deps]
|
|
230
|
+
* @returns {Promise<string>} the written path
|
|
231
|
+
*/
|
|
232
|
+
async function catalogExport(positional, flags, deps = {}) {
|
|
233
|
+
if (!flags.snapshot) throw new Error('catalog export: --snapshot is required (the only export format)')
|
|
234
|
+
if (!flags.out || flags.out === true) throw new Error('catalog export: --out <file> is required')
|
|
235
|
+
const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
|
|
236
|
+
if (!apiBase) throw new Error('catalog export: --api-base (or $SAASLAYER_API_BASE) is required')
|
|
237
|
+
const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
|
|
238
|
+
const a = await callCatalog('catalog export', `${apiBase.replace(/\/$/, '')}/catalog/registry/snapshot`, { method: 'GET', headers: auth })
|
|
239
|
+
const outPath = path.resolve(String(flags.out))
|
|
240
|
+
fs.writeFileSync(outPath, `${JSON.stringify({ meta: a.meta, snapshot: a.snapshot }, null, 2)}\n`)
|
|
241
|
+
console.log(`wrote registry snapshot v${a.snapshot && a.snapshot.version} to ${outPath}`)
|
|
242
|
+
return outPath
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport, rbacRegister, formatApplyResult }
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// `saaslayer deploy` (swf2.7) — self-serve deploy of the customer's project into their connected account.
|
|
2
|
+
// POSTs to the BFF (Bearer id token); the BFF authorizes the caller, resolves the target, and calls the
|
|
3
|
+
// deployer. Handles the two-step cost-confirm (D14): the first call returns NEEDS_CONFIRMATION with an
|
|
4
|
+
// estimate; on y (or --yes) we re-send confirmCost:true.
|
|
5
|
+
'use strict'
|
|
6
|
+
const context = require('../context-store')
|
|
7
|
+
const { apiCall } = require('../api-client')
|
|
8
|
+
const { confirm } = require('../prompt')
|
|
9
|
+
|
|
10
|
+
async function deploy(flags) {
|
|
11
|
+
const project = flags.project || context.get('project')
|
|
12
|
+
if (!project) throw new Error('no project selected — run `saaslayer project use <id>` or pass --project')
|
|
13
|
+
const environment = flags.env || 'prod'
|
|
14
|
+
const services = flags.services ? String(flags.services).split(',').map((s) => s.trim()).filter(Boolean) : undefined
|
|
15
|
+
// Accept the documented kebab flag (--commit-sha) as well as the camelCase form; parseArgs keys by the
|
|
16
|
+
// literal flag, so --commit-sha lands in flags['commit-sha'].
|
|
17
|
+
const commitSha = flags['commit-sha'] || flags.commitSha
|
|
18
|
+
|
|
19
|
+
const attributes = {
|
|
20
|
+
customerId: project,
|
|
21
|
+
environment,
|
|
22
|
+
...(services ? { services } : {}),
|
|
23
|
+
...(flags.region ? { region: flags.region } : {}),
|
|
24
|
+
...(flags.target ? { targetAccountId: flags.target } : {}),
|
|
25
|
+
...(commitSha ? { commitSha } : {}),
|
|
26
|
+
...(flags['admin-email'] ? { adminEmail: flags['admin-email'] } : {}),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
console.log(`Deploying ${services ? services.join(' + ') : 'the default services'} to ${project}/${environment}${flags.region ? '/' + flags.region : ''}…`)
|
|
30
|
+
let res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes }, }, flags)
|
|
31
|
+
|
|
32
|
+
// Cost-confirm (D14): the BFF returns a deployment-estimate with status NEEDS_CONFIRMATION.
|
|
33
|
+
if (res.data && res.data.attributes && res.data.attributes.status === 'NEEDS_CONFIRMATION') {
|
|
34
|
+
const est = res.data.attributes.estimate || {}
|
|
35
|
+
const monthly = est.monthlyUsd != null ? `$${est.monthlyUsd}/mo` : 'an unknown monthly cost'
|
|
36
|
+
console.log(` Estimated cost: ${monthly}.`)
|
|
37
|
+
const ok = flags.yes === true || flags.yes === 'true' || (await confirm('Proceed with the deploy?'))
|
|
38
|
+
if (!ok) { console.log('Aborted.'); return null }
|
|
39
|
+
res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes: { ...attributes, confirmCost: true } } }, flags)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const dep = res.data || {}
|
|
43
|
+
const run = dep.attributes && dep.attributes.run
|
|
44
|
+
console.log(`✅ deploy started: deployment ${dep.id}${run && run.runId ? ` (run ${run.runId})` : ''}`)
|
|
45
|
+
console.log(` watch: saaslayer status --project ${project}${flags.region ? ' --region ' + flags.region : ''}`)
|
|
46
|
+
return dep
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = { deploy }
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// `saaslayer rbac iam-principals set|get`: declare which of your AWS IAM roles are trusted SaaSLayer principals (and
|
|
2
|
+
// their credential scopes) by writing the deployment's SSM parameter in your own account with your AWS credentials.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
const { execFileSync } = require('child_process')
|
|
7
|
+
const { iamPrincipalsParam, validatePrincipalsFile } = require('../iam-session')
|
|
8
|
+
|
|
9
|
+
/** @param {string} cmd @param {string[]} args */
|
|
10
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8' })
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @param {{ deployment?: string, 'service-instance'?: string, region?: string, profile?: string }} flags
|
|
14
|
+
* @returns {{ name: string, awsArgs: string[] }}
|
|
15
|
+
*/
|
|
16
|
+
function target(flags) {
|
|
17
|
+
if (!flags.deployment) throw new Error('rbac iam-principals: --deployment <dep_id> is required')
|
|
18
|
+
const region = flags.region || process.env.AWS_REGION
|
|
19
|
+
if (!region) throw new Error('rbac iam-principals: --region (or $AWS_REGION) is required')
|
|
20
|
+
return {
|
|
21
|
+
name: iamPrincipalsParam(flags.deployment, flags['service-instance'] || '_'),
|
|
22
|
+
awsArgs: ['--region', region, ...(flags.profile ? ['--profile', flags.profile] : [])],
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Validate the principals file and write it to the deployment's SSM parameter.
|
|
28
|
+
* @param {string[]} positional [file]
|
|
29
|
+
* @param {object} flags
|
|
30
|
+
* @param {{ exec?: typeof defaultExec }} [deps]
|
|
31
|
+
*/
|
|
32
|
+
function iamPrincipalsSet(positional, flags, { exec = defaultExec } = {}) {
|
|
33
|
+
if (!positional[0]) throw new Error('rbac iam-principals set: a principals file is required')
|
|
34
|
+
const config = JSON.parse(fs.readFileSync(path.resolve(positional[0]), 'utf8'))
|
|
35
|
+
const errors = validatePrincipalsFile(config)
|
|
36
|
+
if (errors.length) throw new Error(`rbac iam-principals set: ${errors.join('; ')}`)
|
|
37
|
+
const { name, awsArgs } = target(flags)
|
|
38
|
+
exec('aws', ['ssm', 'put-parameter', '--name', name, '--type', 'String', '--overwrite', '--value', JSON.stringify(config), ...awsArgs])
|
|
39
|
+
return name
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Read the deployment's current IAM principals.
|
|
44
|
+
* @param {string[]} positional
|
|
45
|
+
* @param {object} flags
|
|
46
|
+
* @param {{ exec?: typeof defaultExec }} [deps]
|
|
47
|
+
*/
|
|
48
|
+
function iamPrincipalsGet(positional, flags, { exec = defaultExec } = {}) {
|
|
49
|
+
const { name, awsArgs } = target(flags)
|
|
50
|
+
return JSON.parse(exec('aws', ['ssm', 'get-parameter', '--name', name, '--query', 'Parameter.Value', '--output', 'text', ...awsArgs]))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { iamPrincipalsSet, iamPrincipalsGet }
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// `saaslayer status | update | destroy | service add|remove` (swf2.8) — lifecycle over a deployed project.
|
|
2
|
+
// Each resolves the deployment id from (project, env, region) then calls the guarded BFF route. destroy +
|
|
3
|
+
// service-remove (delete custody) are guarded: destroy needs a typed project-name confirmation.
|
|
4
|
+
'use strict'
|
|
5
|
+
const { apiCall } = require('../api-client')
|
|
6
|
+
const { activeProject, resolveDeployment } = require('../deployments')
|
|
7
|
+
const { ask } = require('../prompt')
|
|
8
|
+
|
|
9
|
+
async function status(flags) {
|
|
10
|
+
const project = activeProject(flags)
|
|
11
|
+
const view = await apiCall('GET', `/api/projects/${encodeURIComponent(project)}/deployments`, undefined, flags)
|
|
12
|
+
console.log(`Project ${project}: ${view.instanceCount || 0} deployment(s)`)
|
|
13
|
+
for (const g of view.environments || []) {
|
|
14
|
+
for (const i of g.instances || []) {
|
|
15
|
+
const inst = i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''
|
|
16
|
+
console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst}`)
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return view
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `--param <service>.<Param>=<value>` flags (repeatable) as service-keyed parameters. The value may contain '=' or ','.
|
|
24
|
+
* @param {unknown} raw
|
|
25
|
+
* @returns {Record<string, Record<string, string>>|undefined}
|
|
26
|
+
*/
|
|
27
|
+
function parseParams(raw) {
|
|
28
|
+
if (raw === undefined) return undefined
|
|
29
|
+
const parameters = {}
|
|
30
|
+
for (const entry of Array.isArray(raw) ? raw : [raw]) {
|
|
31
|
+
const m = typeof entry === 'string' ? /^([^.=]+)\.([^=]+)=(.*)$/s.exec(entry) : null
|
|
32
|
+
if (!m) throw new Error('--param expects <service>.<Param>=<value>, e.g. --param user-service.AllowedAppOrigins=https://app.example.com')
|
|
33
|
+
const [, service, name, value] = m
|
|
34
|
+
parameters[service] = { ...(parameters[service] || {}), [name]: value }
|
|
35
|
+
}
|
|
36
|
+
return parameters
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Roll an existing deployment's modules to a new commit (the upgrade path; `deploy` only creates), and/or change its
|
|
40
|
+
// update-safe settings with --param (a settings-only change keeps the current commit).
|
|
41
|
+
async function update(flags) {
|
|
42
|
+
const commitSha = flags['commit-sha'] || flags.commitSha
|
|
43
|
+
const parameters = parseParams(flags.param)
|
|
44
|
+
if (!commitSha && !parameters) throw new Error('update requires --commit-sha <sha> (or --param <service>.<Param>=<value> to change settings)')
|
|
45
|
+
const d = await resolveDeployment(flags)
|
|
46
|
+
console.log(`Updating ${d.project}/${d.env}/${d.region} (${d.deploymentId})${commitSha ? ` to ${commitSha}` : ''}${parameters ? ' with new settings' : ''}…`)
|
|
47
|
+
// Protected envs (staging/prod) require --reason; --force passes the drift gate (audited with the reason).
|
|
48
|
+
const attributes = {}
|
|
49
|
+
if (commitSha) attributes.commitSha = commitSha
|
|
50
|
+
if (parameters) attributes.parameters = parameters
|
|
51
|
+
if (flags.reason) attributes.reason = flags.reason
|
|
52
|
+
if (flags.force === true || flags.force === 'true') attributes.force = true
|
|
53
|
+
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags)
|
|
54
|
+
const status = res && res.data && res.data.attributes && res.data.attributes.status
|
|
55
|
+
console.log(`✅ update started for ${d.deploymentId}${status ? ` (${status})` : ''}`)
|
|
56
|
+
return res
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function destroy(flags) {
|
|
60
|
+
const dataCustody = flags['data-custody']
|
|
61
|
+
if (dataCustody !== 'delete' && dataCustody !== 'retain') throw new Error('destroy requires --data-custody delete|retain')
|
|
62
|
+
// Prod destroy is audited: the deployer requires an explicit reason. Default a sensible one when --reason is omitted.
|
|
63
|
+
const reason = flags.reason || 'destroyed via saaslayer CLI'
|
|
64
|
+
const d = await resolveDeployment(flags)
|
|
65
|
+
console.log(`⚠ This will DESTROY ${d.project}/${d.env}/${d.region} (${d.deploymentId}), data-custody=${dataCustody}.`)
|
|
66
|
+
const typed = flags.yes ? d.project : await ask(`Type the project name "${d.project}" to confirm: `)
|
|
67
|
+
if (typed !== d.project) { console.log('Aborted (name did not match).'); return null }
|
|
68
|
+
const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}?dataCustody=${dataCustody}&reason=${encodeURIComponent(reason)}`, undefined, flags)
|
|
69
|
+
console.log(`✅ destroy started for ${d.deploymentId}`)
|
|
70
|
+
return res
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function serviceAdd(service, flags) {
|
|
74
|
+
if (!service) throw new Error('`service add` requires a service name')
|
|
75
|
+
const d = await resolveDeployment(flags)
|
|
76
|
+
const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services`, { data: { type: 'service', attributes: { service } } }, flags)
|
|
77
|
+
console.log(`✅ adding ${service} to ${d.deploymentId}`)
|
|
78
|
+
return res
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function serviceRemove(service, flags) {
|
|
82
|
+
if (!service) throw new Error('`service remove` requires a service name')
|
|
83
|
+
const dataCustody = flags['data-custody']
|
|
84
|
+
if (dataCustody !== 'delete' && dataCustody !== 'retain') throw new Error('`service remove` requires --data-custody delete|retain')
|
|
85
|
+
const d = await resolveDeployment(flags)
|
|
86
|
+
const res = await apiCall('DELETE', `/api/deployments/${encodeURIComponent(d.deploymentId)}/services/${encodeURIComponent(service)}?dataCustody=${dataCustody}`, undefined, flags)
|
|
87
|
+
console.log(`✅ removing ${service} from ${d.deploymentId} (data-custody=${dataCustody})`)
|
|
88
|
+
return res
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
module.exports = { status, update, destroy, serviceAdd, serviceRemove }
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// `saaslayer login|logout|whoami` — authenticate to the global SaaSLayer user-service via Cognito SRP
|
|
2
|
+
// (headless, D9) and cache tokens locally. Passwordless/FIDO2 opt-in opens a browser (fast-follow).
|
|
3
|
+
'use strict'
|
|
4
|
+
const readline = require('readline')
|
|
5
|
+
const creds = require('../credentials')
|
|
6
|
+
const { resolvePoolConfig, decodeJwt } = require('../config')
|
|
7
|
+
|
|
8
|
+
// Prompt for a value; hidden masks input (passwords). Only used when no flag/env supplies it.
|
|
9
|
+
function prompt(question, { hidden = false } = {}) {
|
|
10
|
+
return new Promise((resolve) => {
|
|
11
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true })
|
|
12
|
+
if (hidden) {
|
|
13
|
+
// Suppress readline's own keystroke echo so only our mask shows (not char+mask interleaved).
|
|
14
|
+
rl._writeToOutput = () => {}
|
|
15
|
+
process.stdout.write(question)
|
|
16
|
+
const onData = (char) => {
|
|
17
|
+
char = String(char)
|
|
18
|
+
if (char === '\u007f' || char === '\b') { process.stdout.write('\b \b'); return } // backspace
|
|
19
|
+
if (['\n', '\r', ''].includes(char)) return
|
|
20
|
+
process.stdout.write('*')
|
|
21
|
+
}
|
|
22
|
+
process.stdin.on('data', onData)
|
|
23
|
+
rl.question('', (answer) => { process.stdin.removeListener('data', onData); rl.close(); process.stdout.write('\n'); resolve(answer) })
|
|
24
|
+
} else {
|
|
25
|
+
rl.question(question, (answer) => { rl.close(); resolve(answer) })
|
|
26
|
+
}
|
|
27
|
+
})
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function login(flags = {}) {
|
|
31
|
+
const { srpLogin } = require('@davidwells/cogneato')
|
|
32
|
+
const pool = await resolvePoolConfig(flags)
|
|
33
|
+
const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
|
|
34
|
+
const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Password: ', { hidden: true }))
|
|
35
|
+
|
|
36
|
+
const step = await srpLogin({ region: pool.region, userPoolId: pool.userPoolId, clientId: pool.clientId, username: email, password }).next()
|
|
37
|
+
const value = step.value || {}
|
|
38
|
+
if (value.code === 'ERROR') throw new Error(`login failed: ${(value.error && (value.error.message || value.error)) || 'unknown error'}`)
|
|
39
|
+
if (value.code !== 'TOKENS') {
|
|
40
|
+
throw new Error(`login requires the '${value.code}' step (passwordless/MFA browser flow not yet wired); use SRP with a password`)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const tokens = value.response.tokens
|
|
44
|
+
const claims = decodeJwt(tokens.idToken)
|
|
45
|
+
const userId = claims.sub
|
|
46
|
+
const expiresAt = Math.floor(Date.now() / 1000) + (Number(tokens.expiresIn) || 3600)
|
|
47
|
+
creds.setUser({
|
|
48
|
+
userId,
|
|
49
|
+
email: claims.email || email,
|
|
50
|
+
env: flags.env || 'prod',
|
|
51
|
+
idToken: tokens.idToken,
|
|
52
|
+
accessToken: tokens.accessToken,
|
|
53
|
+
refreshToken: tokens.refreshToken,
|
|
54
|
+
expiresAt,
|
|
55
|
+
})
|
|
56
|
+
return { userId, email: claims.email || email }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Create a SaaSLayer account via the control-plane signup endpoint (allowlist-gated), then log in.
|
|
60
|
+
async function signup(flags = {}) {
|
|
61
|
+
const base = flags['config-url'] || process.env.SAASLAYER_CONFIG_URL
|
|
62
|
+
if (!base) throw new Error('signup requires --config-url <control-plane API base> (or $SAASLAYER_CONFIG_URL)')
|
|
63
|
+
const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
|
|
64
|
+
const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Choose a password: ', { hidden: true }))
|
|
65
|
+
const res = await fetch(`${String(base).replace(/\/$/, '')}/api/signup`, {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
headers: { 'content-type': 'application/json' },
|
|
68
|
+
body: JSON.stringify({ email, password }),
|
|
69
|
+
})
|
|
70
|
+
const doc = await res.json().catch(() => ({}))
|
|
71
|
+
if (!res.ok) throw new Error(`signup failed (${res.status}): ${doc.error || JSON.stringify(doc)}`)
|
|
72
|
+
// Log in immediately so the account is usable right away.
|
|
73
|
+
return login({ ...flags, email, password })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function whoami() {
|
|
77
|
+
const current = creds.getCurrent()
|
|
78
|
+
if (!current) return null
|
|
79
|
+
return { userId: current.userId, email: current.email, env: current.env }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function logout(flags = {}) {
|
|
83
|
+
// --user accepts an email or a userId; without it, the active account is cleared.
|
|
84
|
+
creds.clear(flags.user ? creds.resolve(flags.user) : undefined)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { login, signup, whoami, logout }
|