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.
Files changed (51) hide show
  1. package/README.md +195 -8
  2. package/bin/saaslayer.js +454 -38
  3. package/package.json +19 -4
  4. package/src/api-client.js +91 -0
  5. package/src/aws-sigv4.js +47 -0
  6. package/src/commands/access-admins.js +73 -0
  7. package/src/commands/accounts.js +54 -0
  8. package/src/commands/activity.js +33 -0
  9. package/src/commands/aws.js +132 -0
  10. package/src/commands/catalog.js +246 -0
  11. package/src/commands/context.js +64 -0
  12. package/src/commands/deploy.js +118 -0
  13. package/src/commands/first-admin.js +42 -0
  14. package/src/commands/foundation.js +405 -0
  15. package/src/commands/lifecycle.js +124 -0
  16. package/src/commands/login.js +261 -0
  17. package/src/commands/machine-trust.js +96 -0
  18. package/src/commands/migrate.js +290 -0
  19. package/src/commands/operations.js +140 -0
  20. package/src/commands/orgs.js +81 -0
  21. package/src/commands/permissions-inspect.js +228 -0
  22. package/src/commands/release-manifest.js +138 -0
  23. package/src/commands/service-principals.js +81 -0
  24. package/src/commands/settings.js +140 -0
  25. package/src/commands/stacks.js +22 -0
  26. package/src/commands/users.js +269 -0
  27. package/src/config.js +49 -0
  28. package/src/context-store.js +37 -0
  29. package/src/credentials.js +285 -0
  30. package/src/deployment-api-auth.js +61 -0
  31. package/src/deployment-auth.js +38 -0
  32. package/src/deployments.js +26 -0
  33. package/src/discovery.js +66 -0
  34. package/src/env-compare.js +143 -0
  35. package/src/foundation-template.js +57 -0
  36. package/src/iam-session.js +67 -0
  37. package/src/migrations-lib.js +15 -0
  38. package/src/module-catalog.js +66 -0
  39. package/src/permissions-request.js +43 -0
  40. package/src/prompt.js +19 -0
  41. package/src/release-manifest.js +334 -0
  42. package/src/scope.js +114 -0
  43. package/src/settings.js +272 -0
  44. package/src/users-api.js +165 -0
  45. package/src/users-import/ids.js +24 -0
  46. package/src/users-import/import.js +292 -0
  47. package/src/users-import/manifest.js +90 -0
  48. package/src/users-import/providers/cognito.js +61 -0
  49. package/src/users-import/providers/index.js +24 -0
  50. package/templates/saaslayer-foundation-region.yml +109 -0
  51. package/templates/{host-account.yml → saaslayer-foundation.yml} +381 -87
@@ -0,0 +1,246 @@
1
+ // `saaslayer permissions model apply|get|export`, `saaslayer permissions owner bootstrap|reconcile` and `saaslayer permissions
2
+ // register`: apply a product's role catalog (PUT /catalog/:product), bootstrap or reconcile its org owners, register a
3
+ // service under its product, and export the published registry snapshot.
4
+ 'use strict'
5
+ const fs = require('fs')
6
+ const path = require('path')
7
+ const { exchangeIamToken } = require('../iam-session')
8
+ const { authHeaders } = require('../deployment-api-auth')
9
+
10
+ /**
11
+ * @typedef {{ type: 'string' | 'number' | 'boolean' | 'string[]' | 'principalRef' | 'ip', required: boolean, nullable?: boolean, pii?: boolean }} AttributeSchema
12
+ * @typedef {{ product: string, service?: string, catalogVersion: number,
13
+ * resources: Record<string, { actions: string[], attributes?: Record<string, AttributeSchema> }>,
14
+ * trustedContext?: boolean, contextSchema?: Record<string, AttributeSchema>,
15
+ * roles: object[], delegation?: object, selfCheck?: object[] }} CatalogManifest
16
+ */
17
+
18
+ /**
19
+ * The API's error messages, each prefixed with its JSON:API source pointer when it has one.
20
+ * @param {{ errors?: Array<{ message?: string, detail?: string, source?: { pointer?: string } }> }} body
21
+ * @returns {string}
22
+ */
23
+ function apiErrorDetail(body) {
24
+ return (body.errors || [])
25
+ .map((e) => {
26
+ const text = e.message || e.detail
27
+ return text && e.source && e.source.pointer ? `${e.source.pointer}: ${text}` : text
28
+ })
29
+ .filter(Boolean).join('; ') || JSON.stringify(body)
30
+ }
31
+
32
+ /**
33
+ * Human-readable summary of an apply/dry-run result.
34
+ * @param {{ product: string, catalogVersion: number, plan: string, dryRun?: boolean,
35
+ * 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[] },
36
+ * warnings?: string[],
37
+ * assignmentCounts?: Record<string, number>, adopted?: Array<{ id: string, orgId: string, assignments: number }>, selfCheck?: Array<{ ok: boolean }>,
38
+ * registry?: { version: number, published: boolean, stalenessSeconds: number } | null }} a
39
+ * @returns {string}
40
+ */
41
+ function formatApplyResult(a) {
42
+ const lines = [`${a.product} catalog v${a.catalogVersion} — plan: ${a.plan}${a.dryRun ? ' (dry run, nothing written)' : ''}`]
43
+ for (const id of a.diff.added) lines.push(` + ${id}`)
44
+ for (const c of a.diff.changed) {
45
+ // A permission whose only change is its condition prints as one `when before -> after` line
46
+ const conditions = c.conditionsChanged || []
47
+ const conditional = new Set(conditions.map((x) => x.permission))
48
+ const unconditioned = (/** @type {string} */ p) => !conditional.has(p.split(' when ')[0])
49
+ const parts = [
50
+ c.fields.length ? `fields: ${c.fields.join(', ')}` : '',
51
+ ...c.permissionsAdded.filter(unconditioned).map((p) => `+${p}`),
52
+ ...c.permissionsRemoved.filter(unconditioned).map((p) => `-${p}`),
53
+ ].filter(Boolean)
54
+ if (parts.length) lines.push(` ~ ${c.id} ${parts.join(' ')}`)
55
+ const when = (/** @type {object|null} */ w) => (w ? JSON.stringify(w) : 'none')
56
+ for (const x of conditions) lines.push(` ~ ${c.id} ${x.permission} when ${when(x.before)} -> ${when(x.after)}`)
57
+ }
58
+ for (const id of a.diff.removed) lines.push(` - ${id} (${(a.assignmentCounts || {})[id] || 0} assignments)`)
59
+ for (const id of a.diff.unchanged) lines.push(` = ${id}`)
60
+ for (const r of a.adopted || []) lines.push(` ^ ${r.id} adopted from org ${r.orgId} (${r.assignments} assignments kept)`)
61
+ for (const line of a.diff.attributes || []) lines.push(` ${line}`)
62
+ const probes = a.selfCheck || []
63
+ lines.push(`selfCheck: ${probes.filter((p) => p.ok).length}/${probes.length} probes pass`)
64
+ for (const w of a.warnings || []) lines.push(`warn: ${w}`)
65
+ const staleness = registryLine(a.registry)
66
+ if (staleness) lines.push(staleness)
67
+ return lines.join('\n')
68
+ }
69
+
70
+ /**
71
+ * The registry publish line: which snapshot version went live and how stale a container may be.
72
+ * @param {{ version: number, published: boolean, stalenessSeconds: number } | null | undefined} registry
73
+ * @returns {string|null}
74
+ */
75
+ function registryLine(registry) {
76
+ if (!registry) return null
77
+ return registry.published
78
+ ? `registry v${registry.version} published — live in every container within ${registry.stalenessSeconds} s`
79
+ : `registry v${registry.version} unchanged`
80
+ }
81
+
82
+ /**
83
+ * @param {string[]} positional [manifestPath]
84
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, 'dry-run'?: boolean, 'allow-orphan'?: boolean, adopt?: boolean }} flags
85
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
86
+ * @returns {Promise<string>} the printed summary
87
+ */
88
+ async function catalogApply(positional, flags, deps = {}) {
89
+ const manifestPath = positional[0]
90
+ if (!manifestPath) throw new Error('permissions model apply: a manifest path is required')
91
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
92
+ if (!apiBase) throw new Error('permissions model apply: --api-base (or $SAASLAYER_API_BASE) is required')
93
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
94
+ /** @type {CatalogManifest} */
95
+ const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
96
+ const query = new URLSearchParams()
97
+ if (flags['dry-run']) query.set('dryRun', 'true')
98
+ if (flags['allow-orphan']) query.set('allowOrphan', 'true')
99
+ if (flags.adopt) query.set('adopt', 'true')
100
+ const qs = query.toString()
101
+ const url = `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(manifest.product)}${qs ? `?${qs}` : ''}`
102
+ const res = await fetch(url, {
103
+ method: 'PUT',
104
+ headers: { ...auth, 'content-type': 'application/json' },
105
+ body: JSON.stringify(manifest),
106
+ })
107
+ const body = await res.json().catch(() => ({}))
108
+ if (!res.ok) {
109
+ throw new Error(`permissions model apply failed (${res.status}): ${apiErrorDetail(body)}`)
110
+ }
111
+ const a = body.data.attributes
112
+ const summary = formatApplyResult(a)
113
+ console.log(summary)
114
+ if (a.plan === 'apply' && !a.dryRun && a.verified !== true) throw new Error('permissions model apply: roles were written but not verified on read-back')
115
+ return summary
116
+ }
117
+
118
+ /**
119
+ * Call a catalog route and return its attributes; throws with the API's error messages.
120
+ * @param {string} label @param {string} url @param {RequestInit} init
121
+ */
122
+ async function callCatalog(label, url, init) {
123
+ const res = await fetch(url, init)
124
+ const body = await res.json().catch(() => ({}))
125
+ if (!res.ok) {
126
+ throw new Error(`${label} failed (${res.status}): ${apiErrorDetail(body)}`)
127
+ }
128
+ return body.data.attributes
129
+ }
130
+
131
+ /**
132
+ * Make a member the first owner of an org (only while it has none). Needs an IAM principal with owners:bootstrap.
133
+ * @param {string[]} positional [product]
134
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, org?: string, user?: string }} flags
135
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
136
+ */
137
+ async function catalogBootstrapOwner(positional, flags, deps = {}) {
138
+ const product = positional[0]
139
+ if (!product) throw new Error('permissions owner bootstrap: a product is required')
140
+ if (!flags.org || !flags.user) throw new Error('permissions owner bootstrap: --org and --user are required')
141
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
142
+ if (!apiBase) throw new Error('permissions owner bootstrap: --api-base (or $SAASLAYER_API_BASE) is required')
143
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
144
+ return callCatalog('permissions owner bootstrap', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/bootstrap-owner`, {
145
+ method: 'POST',
146
+ headers: { ...auth, 'content-type': 'application/json' },
147
+ body: JSON.stringify({ orgId: flags.org, userId: flags.user }),
148
+ })
149
+ }
150
+
151
+ /**
152
+ * Compare every org's owner counter with a live recount; --apply repairs mismatches.
153
+ * @param {string[]} positional [product]
154
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, apply?: boolean, org?: string }} flags
155
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
156
+ */
157
+ async function catalogReconcileOwners(positional, flags, deps = {}) {
158
+ const product = positional[0]
159
+ if (!product) throw new Error('permissions owner reconcile: a product is required')
160
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
161
+ if (!apiBase) throw new Error('permissions owner reconcile: --api-base (or $SAASLAYER_API_BASE) is required')
162
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
163
+ const query = new URLSearchParams()
164
+ if (flags.apply) query.set('apply', 'true')
165
+ if (flags.org) query.set('orgId', flags.org)
166
+ const qs = query.toString()
167
+ return callCatalog('permissions owner reconcile', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/reconcile-owners${qs ? `?${qs}` : ''}`, {
168
+ method: 'POST',
169
+ headers: { ...auth, 'content-type': 'application/json' },
170
+ })
171
+ }
172
+
173
+ /**
174
+ * The catalog currently applied for a product (GET /catalog/:product).
175
+ * @param {string[]} positional [product]
176
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string }} flags
177
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
178
+ * @returns {Promise<{ product: string, catalogVersion: number, contentHash: string, roleIds: string[], manifest: object }>}
179
+ */
180
+ async function catalogGet(positional, flags, deps = {}) {
181
+ const product = positional[0]
182
+ if (!product) throw new Error('permissions model get: a product is required')
183
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
184
+ if (!apiBase) throw new Error('permissions model get: --api-base (or $SAASLAYER_API_BASE) is required')
185
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
186
+ const res = await fetch(`${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}`, { method: 'GET', headers: auth })
187
+ const body = await res.json().catch(() => ({}))
188
+ if (!res.ok) {
189
+ const detail = (body.errors || []).map((e) => e.message || e.detail).filter(Boolean).join('; ') || JSON.stringify(body)
190
+ throw new Error(`permissions model get failed (${res.status}): ${detail}`)
191
+ }
192
+ return body.data.attributes
193
+ }
194
+
195
+ /**
196
+ * Register (upsert) a service's permissions manifest under its product (POST /catalog/register). A service belongs to
197
+ * exactly one product: --product (or the manifest's `product`) is required.
198
+ * @param {string[]} positional [manifestPath]
199
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, product?: string }} flags
200
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
201
+ * @returns {Promise<string>} the printed summary
202
+ */
203
+ async function permissionsRegister(positional, flags, deps = {}) {
204
+ const manifestPath = positional[0]
205
+ if (!manifestPath) throw new Error('permissions register: a manifest path is required')
206
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
207
+ if (!apiBase) throw new Error('permissions register: --api-base (or $SAASLAYER_API_BASE) is required')
208
+ const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
209
+ const product = flags.product || manifest.product
210
+ if (!product) throw new Error('permissions register: --product is required (the product that owns this service)')
211
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
212
+ const a = await callCatalog('register', `${apiBase.replace(/\/$/, '')}/catalog/register`, {
213
+ method: 'POST',
214
+ headers: { ...auth, 'content-type': 'application/json' },
215
+ body: JSON.stringify({ ...manifest, product }),
216
+ })
217
+ const lines = [`registered "${a.service || manifest.service}" under product "${a.product || product}" (${a.resourceCount ?? '?'} resource types)`]
218
+ const staleness = registryLine(a.registry)
219
+ if (staleness) lines.push(staleness)
220
+ const summary = lines.join('\n')
221
+ console.log(summary)
222
+ return summary
223
+ }
224
+
225
+ /**
226
+ * Write the currently published registry snapshot ({ meta, snapshot }) to a file — the pinned registry @saaslayer/permissions
227
+ * direct mode loads (GET /catalog/registry/snapshot).
228
+ * @param {string[]} positional unused
229
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, snapshot?: boolean, out?: string }} flags
230
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
231
+ * @returns {Promise<string>} the written path
232
+ */
233
+ async function catalogExport(positional, flags, deps = {}) {
234
+ if (!flags.snapshot) throw new Error('permissions model export: --snapshot is required (the only export format)')
235
+ if (!flags.out || flags.out === true) throw new Error('permissions model export: --out <file> is required')
236
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
237
+ if (!apiBase) throw new Error('permissions model export: --api-base (or $SAASLAYER_API_BASE) is required')
238
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
239
+ const a = await callCatalog('permissions model export', `${apiBase.replace(/\/$/, '')}/catalog/registry/snapshot`, { method: 'GET', headers: auth })
240
+ const outPath = path.resolve(String(flags.out))
241
+ fs.writeFileSync(outPath, `${JSON.stringify({ meta: a.meta, snapshot: a.snapshot }, null, 2)}\n`)
242
+ console.log(`wrote registry snapshot v${a.snapshot && a.snapshot.version} to ${outPath}`)
243
+ return outPath
244
+ }
245
+
246
+ module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport, permissionsRegister, formatApplyResult }
@@ -0,0 +1,64 @@
1
+ // `saaslayer context` — what the CLI will act as and on: the control-plane account, the deployment login, the AWS
2
+ // profile, the control-plane URL, the org and project (with where each came from) and every cached identity. No tokens.
3
+ 'use strict'
4
+ const context = require('../context-store')
5
+ const { projectIdKind } = require('../scope')
6
+ const { accountsList, deploymentLogins } = require('./accounts')
7
+ const { controlPlaneUrl } = require('../config')
8
+
9
+ /**
10
+ * @param {object} flags
11
+ */
12
+ function contextShow(flags) {
13
+ const current = accountsList().find((a) => a.current)
14
+ const org = context.get('org')
15
+ const project = context.get('project')
16
+ const logins = deploymentLogins()
17
+ const deployment = logins.find((d) => d.current) || null
18
+ const awsEnv = process.env.AWS_PROFILE
19
+ return {
20
+ account: current ? { email: current.email, userId: current.userId, controlPlane: current.env } : null,
21
+ controlPlaneUrl: controlPlaneUrl(flags),
22
+ org: org ? { value: org, source: 'context' } : { value: null, source: null },
23
+ project: project ? { value: project, source: 'context', kind: projectIdKind(project) } : { value: null, source: null, kind: null },
24
+ deployment,
25
+ awsProfile: flags.profile ? { value: flags.profile, source: 'flag' } : awsEnv ? { value: awsEnv, source: 'env' } : { value: null, source: null },
26
+ deploymentLogins: logins,
27
+ identities: accountsList().map((a) => ({ email: a.email, userId: a.userId, controlPlane: a.env, current: a.current, expired: a.expired })),
28
+ }
29
+ }
30
+
31
+ /**
32
+ * @param {ReturnType<typeof contextShow>} ctx
33
+ * @returns {string[]}
34
+ */
35
+ function formatContext(ctx) {
36
+ const lines = [
37
+ ctx.account ? `account: ${ctx.account.email} (${ctx.account.userId}) control plane: ${ctx.account.controlPlane}` : 'account: — (run `saaslayer login`)',
38
+ `control plane url: ${ctx.controlPlaneUrl.value} (from ${ctx.controlPlaneUrl.source})`,
39
+ ctx.org.value ? `org: ${ctx.org.value} (from context)` : 'org: — (run `saaslayer org use <id>`)',
40
+ ctx.project.value ? `project: ${ctx.project.value} (${ctx.project.kind}, from context)` : 'project: — (run `saaslayer project use <id>`)',
41
+ ctx.deployment ? `deployment login: ${deploymentLabel(ctx.deployment)}` : 'deployment login: — (run `saaslayer login --deployment <dep_id|env>`)',
42
+ ctx.awsProfile.value ? `aws profile: ${ctx.awsProfile.value} (from ${ctx.awsProfile.source})` : 'aws profile: — (ambient AWS credentials)',
43
+ 'cached identities:',
44
+ ]
45
+ if (!ctx.identities.length) lines.push(' none — run `saaslayer login`')
46
+ for (const i of ctx.identities) {
47
+ lines.push(`${i.current ? '*' : ' '} ${i.email} [control plane: ${i.controlPlane}]${i.expired === true ? ' (token expired)' : ''}`)
48
+ }
49
+ for (const d of ctx.deploymentLogins) {
50
+ lines.push(`${d.current ? '*' : ' '} ${deploymentLabel(d)}${d.expired === true ? ' (token expired)' : ''}`)
51
+ }
52
+ lines.push('--project/--org/--env on a command override this context for that command; --deployment/--as pick a deployment login; --profile picks the AWS profile.')
53
+ return lines
54
+ }
55
+
56
+ /**
57
+ * @param {{ deploymentId: string, environment: string|null, serviceInstance: string, email: string|null, userId: string }} d
58
+ * @returns {string}
59
+ */
60
+ function deploymentLabel(d) {
61
+ return `${d.deploymentId}${d.environment ? ` [${d.environment}]` : ''} (user-service ${d.serviceInstance}) as ${d.email || d.userId}`
62
+ }
63
+
64
+ module.exports = { contextShow, formatContext }
@@ -0,0 +1,118 @@
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. Then waits for the deploy operation unless --no-wait.
5
+ 'use strict'
6
+ const { resolveScope, printScope } = require('../scope')
7
+ const { apiCall } = require('../api-client')
8
+ const { confirm } = require('../prompt')
9
+ const { finishMutation } = require('./operations')
10
+ const { fetchModuleCatalog, checkModuleIds, checkDependencies, checkParamModules } = require('../module-catalog')
11
+ const { parseSetFlags, readSettingsFile, mergePatches, checkPatch } = require('../settings')
12
+ const { fetchSchema } = require('./settings')
13
+
14
+ /**
15
+ * Module ids from --services a,b and --module (repeatable, comma-separated).
16
+ * @param {object} flags
17
+ * @returns {string[]|undefined}
18
+ */
19
+ function selectedModules(flags) {
20
+ const raw = [flags.services, flags.module].flat().filter((v) => typeof v === 'string')
21
+ const ids = [...new Set(raw.flatMap((v) => v.split(',')).map((s) => s.trim()).filter(Boolean))]
22
+ return ids.length ? ids : undefined
23
+ }
24
+
25
+ /**
26
+ * Check create settings against each module's schema at the revision being deployed (--commit-sha, else the default
27
+ * release the catalog reports) and name the create-only ones. With no known revision the control plane checks them.
28
+ * @param {Record<string, Record<string, unknown>>} parameters
29
+ * @param {string|undefined} commitSha
30
+ * @param {import('../module-catalog').CatalogModule[]} modules
31
+ * @param {object} flags
32
+ */
33
+ async function checkCreateSettings(parameters, commitSha, modules, flags) {
34
+ /** @param {string} id */
35
+ const revisionOf = (id) => commitSha || (modules.find((m) => m.id === id) || { attributes: {} }).attributes.revision
36
+ const ids = Object.keys(parameters)
37
+ if (ids.some((id) => !revisionOf(id))) {
38
+ console.log(' the control plane reports no default release, so settings are checked by the control plane only (pass --commit-sha to check them here first)')
39
+ return parameters
40
+ }
41
+ const schemas = Object.fromEntries(await Promise.all(ids.map(async (id) => [id, await fetchSchema(id, String(revisionOf(id)), flags)])))
42
+ const { patch, createOnly } = checkPatch(parameters, schemas, { op: 'create' })
43
+ if (createOnly.length) console.log(` create-only (fixed once deployed): ${createOnly.join(', ')}`)
44
+ return patch
45
+ }
46
+
47
+ /**
48
+ * @param {Record<string, any>} flags
49
+ * @param {{ interactive?: boolean, confirm?: (question: string) => Promise<boolean> }} [io] test seams: whether a person can
50
+ * answer (default: stdin is a terminal) and how they are asked
51
+ */
52
+ async function deploy(flags, io = {}) {
53
+ const interactive = io.interactive === undefined ? Boolean(process.stdin.isTTY) : io.interactive
54
+ const ask = io.confirm || confirm
55
+ const yes = flags.yes === true || flags.yes === 'true'
56
+ const scope = resolveScope(flags, { env: 'prod' })
57
+ printScope(scope, flags)
58
+ const project = scope.project.value
59
+ const environment = scope.env.value
60
+ const services = selectedModules(flags)
61
+ // Accept the documented kebab flag (--commit-sha) as well as the camelCase form; parseArgs keys by the
62
+ // literal flag, so --commit-sha lands in flags['commit-sha'].
63
+ const commitSha = flags['commit-sha'] || flags.commitSha
64
+ // A settings file is input to this deploy; --set / --param values override it.
65
+ let parameters = mergePatches(typeof flags.settings === 'string' ? readSettingsFile(flags.settings) : undefined, parseSetFlags(flags.param, '--param'), parseSetFlags(flags.set, '--set'))
66
+ // Module ids, dependencies and --param module keys are checked against the catalog before anything is sent.
67
+ if (services || parameters) {
68
+ const modules = await fetchModuleCatalog(flags)
69
+ if (services) {
70
+ checkModuleIds(services, modules)
71
+ checkDependencies(services, modules)
72
+ }
73
+ if (parameters) {
74
+ checkParamModules(parameters, modules)
75
+ parameters = await checkCreateSettings(parameters, commitSha, modules, flags)
76
+ }
77
+ }
78
+
79
+ const attributes = {
80
+ customerId: project,
81
+ environment,
82
+ ...(services ? { services } : {}),
83
+ ...(flags.region ? { region: flags.region } : {}),
84
+ ...(flags.target ? { targetAccountId: flags.target } : {}),
85
+ ...(commitSha ? { commitSha } : {}),
86
+ ...(flags['admin-email'] ? { adminEmail: flags['admin-email'] } : {}),
87
+ ...(parameters ? { parameters } : {}),
88
+ }
89
+
90
+ // Creating a deployment is never implicit: --yes, or a person confirms before the first create request is sent.
91
+ const what = `${services ? services.join(' + ') : 'the default services'} to ${project}/${environment}${flags.region ? '/' + flags.region : ''}`
92
+ if (!yes) {
93
+ if (!interactive) throw new Error(`deploy creates a deployment (${what}); pass --yes to confirm when running non-interactively`)
94
+ if (!(await ask(`Create a deployment: ${what}${flags.target ? ` in account ${flags.target}` : ''}?`))) { console.log('Aborted.'); return null }
95
+ }
96
+ console.log(`Deploying ${what}…`)
97
+ let res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes }, }, flags)
98
+
99
+ // Cost-confirm (D14): the BFF returns a deployment-estimate with status NEEDS_CONFIRMATION.
100
+ if (res.data && res.data.attributes && res.data.attributes.status === 'NEEDS_CONFIRMATION') {
101
+ const est = res.data.attributes.estimate || {}
102
+ const monthly = est.monthlyUsd != null ? `$${est.monthlyUsd}/mo` : 'an unknown monthly cost'
103
+ console.log(` Estimated cost: ${monthly}.`)
104
+ const ok = yes || (interactive && (await ask('Proceed with the deploy?')))
105
+ if (!ok) { console.log('Aborted.'); return null }
106
+ res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes: { ...attributes, confirmCost: true } } }, flags)
107
+ }
108
+
109
+ const dep = res.data || {}
110
+ const run = dep.attributes && dep.attributes.run
111
+ console.log(`✅ deploy started: deployment ${dep.id}${run && run.runId ? ` (run ${run.runId})` : ''}`)
112
+ console.log(` status: saaslayer status --project ${project}${flags.region ? ' --region ' + flags.region : ''}`)
113
+ await finishMutation({ response: res, deploymentId: dep.id, flags })
114
+ if (res.operation) dep.operation = res.operation
115
+ return dep
116
+ }
117
+
118
+ module.exports = { deploy }
@@ -0,0 +1,42 @@
1
+ // `saaslayer first-admin resend|recover` (authorization matrix B2/B3): resend the designated first admin's first sign-in,
2
+ // or designate a new first admin when no usable access admin remains; waits for the operation that does it.
3
+ 'use strict'
4
+ const { apiCall } = require('../api-client')
5
+ const { resolveDeployment } = require('../deployments')
6
+ const { finishMutation, requestKeyHeaders } = require('./operations')
7
+
8
+ const USAGE = 'usage: saaslayer first-admin <resend|recover> [--deployment ID | --project P --env E --region R] [--email E --reason TEXT] [--suid ID] [--no-wait]'
9
+
10
+ /**
11
+ * The request attributes for a subcommand; refusals happen before anything is sent.
12
+ * @param {string|undefined} sub
13
+ * @param {Record<string, unknown>} flags
14
+ * @returns {{ action: 'resend'|'recover', adminEmail?: string, adminSuid?: string, reason?: string }}
15
+ */
16
+ function requestOf(sub, flags) {
17
+ /** @param {unknown} v */
18
+ const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
19
+ const reason = text(flags.reason)
20
+ if (sub === 'resend') return { action: 'resend', ...(reason ? { reason } : {}) }
21
+ if (sub !== 'recover') throw new Error(USAGE)
22
+ const adminEmail = text(flags.email)
23
+ if (!adminEmail) throw new Error('first-admin recover needs --email <new admin email>')
24
+ if (!reason) throw new Error('first-admin recover needs --reason <text> (recorded in the deployment activity)')
25
+ const adminSuid = text(flags.suid)
26
+ return { action: 'recover', adminEmail, ...(adminSuid ? { adminSuid } : {}), reason }
27
+ }
28
+
29
+ /**
30
+ * @param {string|undefined} sub resend | recover
31
+ * @param {Record<string, unknown>} flags
32
+ */
33
+ async function firstAdminCommand(sub, flags) {
34
+ const attributes = requestOf(sub, flags)
35
+ const deploymentId = typeof flags.deployment === 'string' ? flags.deployment : (await resolveDeployment(flags)).deploymentId
36
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/admin-bootstrap`, { data: { type: 'admin-bootstrap-requests', attributes } }, flags, { headers: requestKeyHeaders() })
37
+ const attrs = (res.data && res.data.attributes) || {}
38
+ console.log(`first-admin ${attributes.action} started: operation ${attrs.operationId || '—'} on deployment ${deploymentId}`)
39
+ return finishMutation({ response: res, deploymentId, flags })
40
+ }
41
+
42
+ module.exports = { firstAdminCommand }