saaslayer 0.3.0 → 0.4.1

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 (65) hide show
  1. package/README.md +199 -18
  2. package/bin/saaslayer.js +335 -62
  3. package/package.json +3 -2
  4. package/src/aws-sigv4.js +74 -26
  5. package/src/commands/access-admins.js +2 -2
  6. package/src/commands/admin-allowlist.js +23 -3
  7. package/src/commands/api-keys.js +83 -0
  8. package/src/commands/audit.js +77 -0
  9. package/src/commands/aws.js +355 -82
  10. package/src/commands/binding-handoff.js +174 -0
  11. package/src/commands/bindings.js +111 -0
  12. package/src/commands/catalog.js +30 -3
  13. package/src/commands/deploy.js +49 -11
  14. package/src/commands/env-export.js +58 -0
  15. package/src/commands/first-admin.js +15 -4
  16. package/src/commands/foundation.js +75 -117
  17. package/src/commands/hooks.js +271 -0
  18. package/src/commands/integration-credentials.js +1 -1
  19. package/src/commands/lifecycle.js +149 -24
  20. package/src/commands/login-domain.js +259 -0
  21. package/src/commands/permission-orgs.js +80 -0
  22. package/src/commands/release-manifest.js +17 -8
  23. package/src/commands/service-principals.js +42 -5
  24. package/src/commands/settings.js +21 -5
  25. package/src/commands/sms-registration.js +182 -0
  26. package/src/commands/sms.js +178 -0
  27. package/src/commands/social.js +265 -0
  28. package/src/commands/support-staff.js +72 -0
  29. package/src/commands/users-management.js +2 -20
  30. package/src/commands/users.js +56 -11
  31. package/src/commands/versions.js +61 -0
  32. package/src/connection-proof.js +41 -0
  33. package/src/deployments.js +14 -2
  34. package/src/foundation-change-set.js +180 -0
  35. package/src/foundation-home.js +121 -0
  36. package/src/foundation-template.js +51 -10
  37. package/src/foundation-trust-write.js +379 -0
  38. package/src/iam-session.js +14 -8
  39. package/src/login-domain.js +138 -0
  40. package/src/login-methods.js +118 -0
  41. package/src/module-catalog.js +3 -2
  42. package/src/release-manifest.js +11 -4
  43. package/src/scope.js +3 -1
  44. package/src/settings.js +85 -13
  45. package/src/sms/number.js +37 -0
  46. package/src/sms/registration-fields.js +167 -0
  47. package/src/sms/registration-validate.js +151 -0
  48. package/src/sms/registration.js +216 -0
  49. package/src/sms/release.js +55 -0
  50. package/src/sms/scope.js +86 -0
  51. package/src/sms/status.js +181 -0
  52. package/src/ssm-api.js +31 -0
  53. package/src/trust-entries.js +350 -0
  54. package/src/user-service-instance.js +27 -0
  55. package/src/users-api.js +55 -8
  56. package/src/users-import/checkpoint.js +76 -0
  57. package/src/users-import/import.js +233 -24
  58. package/src/versions.js +80 -0
  59. package/templates/bootstrap/saaslayer-bootstrap-permission-set-inline-policy.json +148 -0
  60. package/templates/bootstrap/saaslayer-bootstrap-policy-email-sender.json +22 -0
  61. package/templates/bootstrap/saaslayer-bootstrap-policy-sms-number.json +22 -0
  62. package/templates/bootstrap/saaslayer-bootstrap-policy.json +114 -0
  63. package/templates/bootstrap/saaslayer-bootstrap-trust-policy.json +18 -0
  64. package/templates/saaslayer-foundation-region.yml +45 -1
  65. package/templates/saaslayer-foundation.yml +759 -309
@@ -0,0 +1,174 @@
1
+ // `saaslayer bindings handoff <start|prepare|freeze|sync|cutover|rollback|complete|status> <bindingId>`: moves a consumer
2
+ // binding to a replacement deployment (ADR 0007 §2.1) one checked step at a time, and prints the state and the next step.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const { apiBase, jsonApiCall } = require('../api-client')
7
+
8
+ const STEPS = ['start', 'prepare', 'freeze', 'sync', 'cutover', 'rollback', 'complete', 'status']
9
+ const USAGE = `usage: saaslayer bindings handoff <${STEPS.join('|')}> <bindingId> (see saaslayer --help)`
10
+ const ROLLBACK_MODES = ['reverse-migration', 'accept-loss']
11
+
12
+ /**
13
+ * @typedef {{ fromDeploymentId: string, toDeploymentId: string, state: string, startedAt: string, switchedAt: string|null,
14
+ * consumersConfirmed: boolean }} Handoff
15
+ * @typedef {{ action: string, state: string, at: string, actor: string, fromDeploymentId: string, toDeploymentId: string,
16
+ * evidence: object }} HandoffRecord
17
+ */
18
+
19
+ /**
20
+ * What the owner does after the handoff reaches a state.
21
+ * @param {object} flags
22
+ * @param {string} bindingId
23
+ * @param {Handoff} h
24
+ * @returns {string}
25
+ */
26
+ function nextStep(flags, bindingId, h) {
27
+ const steps = {
28
+ started: `build and validate release candidates from ${apiBase(flags)}/api/discovery/${h.toDeploymentId}; then record the checkpoints: saaslayer bindings handoff prepare ${bindingId} --validation-writes FILE --reader-role-confirmed --consumer NAME --consumers-confirmed`,
29
+ frozen: `run the final sync (services/user-service: node scripts/migrate-pool.js --delta --commit > report.log), then: saaslayer bindings handoff sync ${bindingId} --report report.log`,
30
+ synced: `release the static consumers' rebuilt candidates, then: saaslayer bindings handoff cutover ${bindingId}`,
31
+ switched: `turn WriteFreeze off on ${h.toDeploymentId} (saaslayer settings set); runtime consumers move on their next refresh; after the observation window: saaslayer bindings handoff complete ${bindingId}`,
32
+ rolled_back: `turn WriteFreeze and AdminMaintenance off on ${h.fromDeploymentId} (saaslayer settings set) and re-point any released consumers`,
33
+ completed: `${h.fromDeploymentId} is kept until its owner retires it with a custody decision (retain or delete)`,
34
+ }
35
+ return steps[h.state] || ''
36
+ }
37
+
38
+ /**
39
+ * Rethrow a refusal with its detail, which names what the step is missing.
40
+ * @param {() => Promise<object>} call
41
+ */
42
+ async function withDetail(call) {
43
+ try {
44
+ return await call()
45
+ } catch (err) {
46
+ const detail = err && err.body && Array.isArray(err.body.errors) && err.body.errors[0] && err.body.errors[0].detail
47
+ if (detail) err.message = `${err.message} (${detail})`
48
+ throw err
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Read a JSON file named by a flag.
54
+ * @param {string} flag
55
+ * @param {string} file
56
+ */
57
+ function readFlagFile(flag, file) {
58
+ try {
59
+ return fs.readFileSync(path.resolve(file), 'utf8')
60
+ } catch (err) {
61
+ throw new Error(`--${flag}: cannot read ${file} (${err.code || err.message})`)
62
+ }
63
+ }
64
+
65
+ /**
66
+ * The validation-write ledger: a JSON array of { description, disposition: reverted|overwritten }.
67
+ * @param {string} file
68
+ */
69
+ function validationWrites(file) {
70
+ let list
71
+ try { list = JSON.parse(readFlagFile('validation-writes', file)) } catch (err) {
72
+ if (err.message.startsWith('--validation-writes')) throw err
73
+ }
74
+ if (!Array.isArray(list)) throw new Error('--validation-writes must be a JSON array of { "description", "disposition": "reverted"|"overwritten" } ([] when none)')
75
+ return list
76
+ }
77
+
78
+ /**
79
+ * The delta compare from a migrate-pool --delta report: the report as JSON, or the script's output with its `report:` line.
80
+ * @param {string} file
81
+ */
82
+ function compareReport(file) {
83
+ const text = readFlagFile('report', file)
84
+ let report
85
+ try { report = JSON.parse(text) } catch {
86
+ const at = text.lastIndexOf('report:')
87
+ try { report = at >= 0 ? JSON.parse(text.slice(at + 'report:'.length)) : null } catch { report = null }
88
+ }
89
+ if (!report || typeof report.compare !== 'object' || report.compare === null) {
90
+ throw new Error(`--report ${file} has no delta compare (run services/user-service scripts/migrate-pool.js --delta --commit)`)
91
+ }
92
+ return report.compare
93
+ }
94
+
95
+ /**
96
+ * The prepare checkpoints from flags; at least one is required.
97
+ * @param {object} flags
98
+ */
99
+ function prepareAttributes(flags) {
100
+ const attributes = {}
101
+ if (flags['validation-writes'] !== undefined) attributes.validationWrites = validationWrites(String(flags['validation-writes']))
102
+ if (flags['reader-role-confirmed'] === true) attributes.readerRoleConfirmed = true
103
+ if (flags.consumer !== undefined) attributes.consumers = [].concat(flags.consumer).map(String)
104
+ if (flags['consumers-confirmed'] === true) attributes.consumersConfirmed = true
105
+ if (!Object.keys(attributes).length) throw new Error('prepare needs at least one of --validation-writes FILE, --reader-role-confirmed, --consumer NAME, --consumers-confirmed')
106
+ return attributes
107
+ }
108
+
109
+ /**
110
+ * The request body a step sends (undefined for the steps that take none).
111
+ * @param {object} flags
112
+ * @param {string} step
113
+ */
114
+ function stepAttributes(flags, step) {
115
+ if (step === 'start') {
116
+ if (typeof flags.to !== 'string' || !flags.to) throw new Error('start requires --to <dep_id> (the replacement deployment)')
117
+ return { toDeploymentId: flags.to }
118
+ }
119
+ if (step === 'prepare') return prepareAttributes(flags)
120
+ if (step === 'sync') {
121
+ if (typeof flags.report !== 'string') throw new Error('sync requires --report FILE (the migrate-pool --delta --commit report)')
122
+ return { compare: compareReport(flags.report) }
123
+ }
124
+ if (step === 'rollback') {
125
+ if (flags.mode === undefined) return {}
126
+ if (!ROLLBACK_MODES.includes(flags.mode)) throw new Error(`--mode must be ${ROLLBACK_MODES.join(' or ')}`)
127
+ return { mode: flags.mode }
128
+ }
129
+ return undefined
130
+ }
131
+
132
+ /**
133
+ * One line for the handoff, or `no handoff` when none has started.
134
+ * @param {string} bindingId
135
+ * @param {string} deploymentId
136
+ * @param {Handoff|null} h
137
+ */
138
+ function handoffLine(bindingId, deploymentId, h) {
139
+ if (!h) return `consumer binding ${bindingId}: no handoff (binding resolves ${deploymentId})`
140
+ return `consumer binding ${bindingId}: handoff ${h.fromDeploymentId} -> ${h.toDeploymentId} is ${h.state} (binding resolves ${deploymentId})`
141
+ }
142
+
143
+ /**
144
+ * Run one handoff step (or show the status) for a consumer binding.
145
+ * @param {object} flags
146
+ * @param {string} [step]
147
+ * @param {string} [bindingId]
148
+ */
149
+ async function bindingsHandoff(flags, step, bindingId) {
150
+ if (!STEPS.includes(step)) throw new Error(USAGE)
151
+ if (!bindingId) throw new Error(`bindings handoff ${step} requires a binding id (bnd_…)`)
152
+ const base = `/api/bindings/${encodeURIComponent(bindingId)}/handoff`
153
+ if (step === 'status') {
154
+ const status = (await withDetail(() => jsonApiCall('GET', base, undefined, flags))).data.attributes
155
+ if (flags.json) console.log(JSON.stringify(status, null, 2))
156
+ else {
157
+ console.log(handoffLine(bindingId, status.deploymentId, status.handoff))
158
+ for (const r of status.history) console.log(` ${r.at} ${r.action} -> ${r.state} by ${r.actor}`)
159
+ }
160
+ return status
161
+ }
162
+ const attributes = stepAttributes(flags, step)
163
+ const body = attributes === undefined ? undefined : { data: { type: 'binding-handoffs', attributes } }
164
+ const binding = (await withDetail(() => jsonApiCall('POST', step === 'start' ? base : `${base}/${step}`, body, flags))).data.attributes
165
+ if (flags.json) console.log(JSON.stringify(binding, null, 2))
166
+ else {
167
+ console.log(handoffLine(bindingId, binding.deploymentId, binding.handoff))
168
+ const next = binding.handoff && nextStep(flags, bindingId, binding.handoff)
169
+ if (next) console.log(`next: ${next}`)
170
+ }
171
+ return binding
172
+ }
173
+
174
+ module.exports = { bindingsHandoff }
@@ -0,0 +1,111 @@
1
+ // `saaslayer bindings create|list|show`: consumer bindings, an org's persistent pointer at one deployment and its chosen
2
+ // user-service / permissions-service instances, each read by consumers at its discovery URL. Org owners only.
3
+ 'use strict'
4
+ const context = require('../context-store')
5
+ const { apiBase, jsonApiCall } = require('../api-client')
6
+ const { resolveDeployment } = require('../deployments')
7
+
8
+ // The deployer identity kernel's instance label grammar (letter-first, alnum, at most 12 characters).
9
+ const INSTANCE = /^[a-z][a-z0-9]{0,11}$/
10
+
11
+ /**
12
+ * @typedef {{ bindingId: string, orgId: string, deploymentId: string, label: string, handoff: object|null, createdAt: string,
13
+ * serviceRefs: { users: string, permissions: string } }} Binding
14
+ */
15
+
16
+ /**
17
+ * The public discovery URL consumers read a binding from.
18
+ * @param {object} flags
19
+ * @param {string} bindingId
20
+ */
21
+ function bindingDiscoveryUrl(flags, bindingId) {
22
+ return `${apiBase(flags)}/api/discovery/bindings/${encodeURIComponent(bindingId)}`
23
+ }
24
+
25
+ /**
26
+ * A binding from a JSON:API resource, with its discovery URL.
27
+ * @param {object} flags
28
+ * @param {{ id: string, attributes: Binding }} resource
29
+ * @returns {Binding & { discoveryUrl: string }}
30
+ */
31
+ function withUrl(flags, resource) {
32
+ return { ...resource.attributes, discoveryUrl: bindingDiscoveryUrl(flags, resource.id) }
33
+ }
34
+
35
+ /**
36
+ * `service@<instance>` for an instance flag, or undefined when the flag is absent (the default instance).
37
+ * @param {object} flags
38
+ * @param {string} flag
39
+ * @param {string} service
40
+ */
41
+ function instanceRef(flags, flag, service) {
42
+ const value = flags[flag]
43
+ if (value === undefined) return undefined
44
+ if (typeof value !== 'string' || !INSTANCE.test(value)) throw new Error(`--${flag} must be an instance label (letter-first, lowercase alphanumeric, at most 12 characters)`)
45
+ return `${service}@${value}`
46
+ }
47
+
48
+ /**
49
+ * Create a consumer binding to one deployment (--deployment dep_…, or the project's --env deployment) and print its id
50
+ * and discovery URL. --user-service-instance / --permissions-instance pick named instances (default: the default ones).
51
+ * @param {object} flags
52
+ */
53
+ async function bindingsCreate(flags) {
54
+ const label = typeof flags.label === 'string' ? flags.label.trim() : ''
55
+ if (!label) throw new Error('--label is required')
56
+ const users = instanceRef(flags, 'user-service-instance', 'user-service')
57
+ const permissions = instanceRef(flags, 'permissions-instance', 'permissions-service')
58
+ if (!flags.deployment && !flags.env) throw new Error('--deployment <dep_id> or --env <environment> is required')
59
+ const deploymentId = flags.deployment || (await resolveDeployment(flags)).deploymentId
60
+ const serviceRefs = { ...(users ? { users } : {}), ...(permissions ? { permissions } : {}) }
61
+ const attributes = { deploymentId, label, ...(users || permissions ? { serviceRefs } : {}) }
62
+ const doc = await jsonApiCall('POST', '/api/bindings', { data: { type: 'bindings', attributes } }, flags)
63
+ const binding = withUrl(flags, doc.data)
64
+ if (flags.json) console.log(JSON.stringify(binding, null, 2))
65
+ else {
66
+ console.log(`created consumer binding ${binding.bindingId} (${binding.label}) -> ${binding.deploymentId}`)
67
+ console.log(`discovery URL: ${binding.discoveryUrl}`)
68
+ }
69
+ return binding
70
+ }
71
+
72
+ /**
73
+ * List the consumer bindings of the orgs the caller owns (--org, else the active org, narrows to one).
74
+ * @param {object} flags
75
+ */
76
+ async function bindingsList(flags) {
77
+ const orgId = flags.org || context.get('org')
78
+ const doc = await jsonApiCall('GET', `/api/bindings${orgId ? `?orgId=${encodeURIComponent(orgId)}` : ''}`, undefined, flags)
79
+ const rows = (doc.data || []).map((r) => withUrl(flags, r))
80
+ if (flags.json) console.log(JSON.stringify(rows, null, 2))
81
+ else if (!rows.length) console.log('no consumer bindings')
82
+ else {
83
+ for (const b of rows) console.log(`${b.bindingId} ${b.label} ${b.deploymentId} users=${b.serviceRefs.users} permissions=${b.serviceRefs.permissions} ${b.discoveryUrl}`)
84
+ }
85
+ return rows
86
+ }
87
+
88
+ /**
89
+ * Show one consumer binding and its discovery URL.
90
+ * @param {object} flags
91
+ * @param {string} [bindingId]
92
+ */
93
+ async function bindingsShow(flags, bindingId) {
94
+ if (!bindingId) throw new Error('bindings show requires a binding id (bnd_…)')
95
+ const doc = await jsonApiCall('GET', `/api/bindings/${encodeURIComponent(bindingId)}`, undefined, flags)
96
+ const b = withUrl(flags, doc.data)
97
+ if (flags.json) console.log(JSON.stringify(b, null, 2))
98
+ else {
99
+ console.log(`consumer binding ${b.bindingId} (${b.label})`)
100
+ console.log(` org: ${b.orgId}`)
101
+ console.log(` deployment: ${b.deploymentId}`)
102
+ console.log(` users: ${b.serviceRefs.users}`)
103
+ console.log(` permissions: ${b.serviceRefs.permissions}`)
104
+ console.log(` handoff: ${b.handoff ? JSON.stringify(b.handoff) : 'none'}`)
105
+ console.log(` created: ${b.createdAt}`)
106
+ console.log(` discovery: ${b.discoveryUrl}`)
107
+ }
108
+ return b
109
+ }
110
+
111
+ module.exports = { bindingsCreate, bindingsList, bindingsShow, bindingDiscoveryUrl }
@@ -149,10 +149,36 @@ async function catalogBootstrapOwner(positional, flags, deps = {}) {
149
149
  }
150
150
 
151
151
  /**
152
- * Compare every org's owner counter with a live recount; --apply repairs mismatches.
152
+ * @typedef {{ ownerRole: string, wouldGrant: number, granted: number, orgs: number,
153
+ * checkpoint?: { runId?: string, cursor?: string|null, done?: boolean } | null }} OwnerCompletion
154
+ * @typedef {{ applied?: boolean, orgs?: Array<{ orgId: string, counter: number, actual: number, ok: boolean }>,
155
+ * completion?: OwnerCompletion }} ReconcileResult
156
+ */
157
+
158
+ /**
159
+ * Human-readable summary of a reconcile-owners result: counter drift per org, then the owner completion counts.
160
+ * @param {ReconcileResult} r
161
+ * @returns {string}
162
+ */
163
+ function formatReconcileResult(r) {
164
+ const lines = (r.orgs || []).map((o) => `${o.ok ? 'ok ' : 'DRIFT'} ${o.orgId} counter=${o.counter} actual=${o.actual}`)
165
+ lines.push(r.applied ? 'repaired mismatched counters' : 'report only (pass --apply to repair)')
166
+ const c = r.completion
167
+ if (c) {
168
+ const cp = c.checkpoint
169
+ const at = cp ? ` (checkpoint ${cp.runId} ${cp.done ? 'done' : `resumes after ${cp.cursor}`})` : ''
170
+ lines.push(`completion ${c.ownerRole}: ${c.wouldGrant} would be granted, ${c.granted} granted across ${c.orgs} orgs${at}`)
171
+ }
172
+ return lines.join('\n')
173
+ }
174
+
175
+ /**
176
+ * Compare every org's owner counter with a live recount; --apply repairs mismatches. --complete-owners also grants the
177
+ * product's ownerRole to every platform owner (saaslayer:org-owner) missing it (dry run unless --apply).
153
178
  * @param {string[]} positional [product]
154
- * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, apply?: boolean, org?: string }} flags
179
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, apply?: boolean, org?: string, 'complete-owners'?: boolean }} flags
155
180
  * @param {{ exchange?: typeof exchangeIamToken }} [deps]
181
+ * @returns {Promise<ReconcileResult>}
156
182
  */
157
183
  async function catalogReconcileOwners(positional, flags, deps = {}) {
158
184
  const product = positional[0]
@@ -161,6 +187,7 @@ async function catalogReconcileOwners(positional, flags, deps = {}) {
161
187
  if (!apiBase) throw new Error('permissions owner reconcile: --api-base (or $SAASLAYER_API_BASE) is required')
162
188
  const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
163
189
  const query = new URLSearchParams()
190
+ if (flags['complete-owners']) query.set('completeOwners', 'true')
164
191
  if (flags.apply) query.set('apply', 'true')
165
192
  if (flags.org) query.set('orgId', flags.org)
166
193
  const qs = query.toString()
@@ -243,4 +270,4 @@ async function catalogExport(positional, flags, deps = {}) {
243
270
  return outPath
244
271
  }
245
272
 
246
- module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport, permissionsRegister, formatApplyResult }
273
+ module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport, permissionsRegister, formatApplyResult, formatReconcileResult }
@@ -1,4 +1,4 @@
1
- // `saaslayer deploy` (swf2.7) — self-serve deploy of the customer's project into their connected account.
1
+ // `saaslayer deploy` (swf2.7) — self-serve deploy of the customer's project into a SaaSLayer pool account or their connected account.
2
2
  // POSTs to the BFF (Bearer id token); the BFF authorizes the caller, resolves the target, and calls the
3
3
  // deployer. Handles the two-step cost-confirm (D14): the first call returns NEEDS_CONFIRMATION with an
4
4
  // estimate; on y (or --yes) we re-send confirmCost:true. Then waits for the deploy operation unless --no-wait.
@@ -10,6 +10,8 @@ const { finishMutation } = require('./operations')
10
10
  const { fetchModuleCatalog, checkModuleIds, checkDependencies, checkParamModules } = require('../module-catalog')
11
11
  const { parseSetFlags, readSettingsFile, mergePatches, checkPatch } = require('../settings')
12
12
  const { fetchSchema } = require('./settings')
13
+ const { USER_SERVICE, signInChange, signInRefusalHint } = require('../login-methods')
14
+ const { releaseChoice, checkReleaseChoice } = require('../versions')
13
15
 
14
16
  /**
15
17
  * Module ids from --services a,b and --module (repeatable, comma-separated).
@@ -22,15 +24,34 @@ function selectedModules(flags) {
22
24
  return ids.length ? ids : undefined
23
25
  }
24
26
 
27
+ /**
28
+ * Where the deploy runs from --hosting: hosted (a SaaSLayer pool account) or byoa (your connected AWS account); absent,
29
+ * the control plane uses the project's connected account when there is one, else hosts it.
30
+ * @param {Record<string, any>} flags
31
+ * @returns {'hosted'|'byoa'|undefined}
32
+ */
33
+ function hostingChoice(flags) {
34
+ if (flags.hosting === undefined) return undefined
35
+ if (flags.hosting !== 'hosted' && flags.hosting !== 'byoa') throw new Error('--hosting must be hosted (a SaaSLayer pool account) or byoa (your connected AWS account)')
36
+ if (flags.hosting === 'hosted' && flags.target) throw new Error('--target names your own account: drop it, or use --hosting byoa')
37
+ return flags.hosting
38
+ }
39
+
25
40
  /**
26
41
  * 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.
42
+ * release the catalog reports) and name the create-only ones. A --version or --channel names no commit here (versions
43
+ * carry none), so the control plane checks them, as it does when no revision is known.
28
44
  * @param {Record<string, Record<string, unknown>>} parameters
29
- * @param {string|undefined} commitSha
45
+ * @param {import('../versions').ReleaseChoice|null} choice
30
46
  * @param {import('../module-catalog').CatalogModule[]} modules
31
47
  * @param {object} flags
32
48
  */
33
- async function checkCreateSettings(parameters, commitSha, modules, flags) {
49
+ async function checkCreateSettings(parameters, choice, modules, flags) {
50
+ if (choice && !('commitSha' in choice)) {
51
+ console.log(' settings for a version are checked by the control plane when it resolves the version')
52
+ return parameters
53
+ }
54
+ const commitSha = choice ? choice.commitSha : undefined
34
55
  /** @param {string} id */
35
56
  const revisionOf = (id) => commitSha || (modules.find((m) => m.id === id) || { attributes: {} }).attributes.revision
36
57
  const ids = Object.keys(parameters)
@@ -53,14 +74,14 @@ async function deploy(flags, io = {}) {
53
74
  const interactive = io.interactive === undefined ? Boolean(process.stdin.isTTY) : io.interactive
54
75
  const ask = io.confirm || confirm
55
76
  const yes = flags.yes === true || flags.yes === 'true'
77
+ const hosting = hostingChoice(flags)
56
78
  const scope = resolveScope(flags, { env: 'prod' })
57
79
  printScope(scope, flags)
58
80
  const project = scope.project.value
59
81
  const environment = scope.env.value
60
82
  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
83
+ // The release to start on: --version, --channel or --commit-sha (none: the control plane's default, stable).
84
+ const choice = releaseChoice(flags)
64
85
  // A settings file is input to this deploy; --set / --param values override it.
65
86
  let parameters = mergePatches(typeof flags.settings === 'string' ? readSettingsFile(flags.settings) : undefined, parseSetFlags(flags.param, '--param'), parseSetFlags(flags.set, '--set'))
66
87
  // Module ids, dependencies and --param module keys are checked against the catalog before anything is sent.
@@ -72,21 +93,32 @@ async function deploy(flags, io = {}) {
72
93
  }
73
94
  if (parameters) {
74
95
  checkParamModules(parameters, modules)
75
- parameters = await checkCreateSettings(parameters, commitSha, modules, flags)
96
+ parameters = await checkCreateSettings(parameters, choice, modules, flags)
76
97
  }
77
98
  }
78
99
 
100
+ // The permanent primary and any added secondary: what they need is checked, and their preview shown, before anything is sent.
101
+ const adminPhoneNumber = typeof flags['admin-phone-number'] === 'string' ? flags['admin-phone-number'].trim() : undefined
102
+ const signIn = signInChange({ op: 'create', values: (parameters && parameters[USER_SERVICE]) || {}, adminPhoneNumber, env: environment })
103
+ if (signIn.problems.length) throw new Error(signIn.problems.join('\n'))
104
+ for (const line of signIn.preview) console.log(` ${line}`)
105
+
79
106
  const attributes = {
80
107
  customerId: project,
81
108
  environment,
82
109
  ...(services ? { services } : {}),
83
110
  ...(flags.region ? { region: flags.region } : {}),
84
111
  ...(flags.target ? { targetAccountId: flags.target } : {}),
85
- ...(commitSha ? { commitSha } : {}),
112
+ ...(hosting ? { hosting } : {}),
113
+ ...(choice || {}),
86
114
  ...(flags['admin-email'] ? { adminEmail: flags['admin-email'] } : {}),
115
+ ...(adminPhoneNumber ? { adminPhoneNumber } : {}),
87
116
  ...(parameters ? { parameters } : {}),
88
117
  }
89
118
 
119
+ // A version or channel the control plane doesn't know (or can't take) is refused before the create.
120
+ await checkReleaseChoice(choice, flags)
121
+
90
122
  // Creating a deployment is never implicit: --yes, or a person confirms before the first create request is sent.
91
123
  const what = `${services ? services.join(' + ') : 'the default services'} to ${project}/${environment}${flags.region ? '/' + flags.region : ''}`
92
124
  if (!yes) {
@@ -94,7 +126,13 @@ async function deploy(flags, io = {}) {
94
126
  if (!(await ask(`Create a deployment: ${what}${flags.target ? ` in account ${flags.target}` : ''}?`))) { console.log('Aborted.'); return null }
95
127
  }
96
128
  console.log(`Deploying ${what}…`)
97
- let res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes }, }, flags)
129
+ /** @param {object} body */
130
+ const create = (body) => apiCall('POST', '/api/deployments', body, flags).catch((err) => {
131
+ const hint = signInRefusalHint(err, environment)
132
+ if (hint) err.message += `\n${hint}`
133
+ throw err
134
+ })
135
+ let res = await create({ data: { type: 'deployments', attributes } })
98
136
 
99
137
  // Cost-confirm (D14): the BFF returns a deployment-estimate with status NEEDS_CONFIRMATION.
100
138
  if (res.data && res.data.attributes && res.data.attributes.status === 'NEEDS_CONFIRMATION') {
@@ -103,7 +141,7 @@ async function deploy(flags, io = {}) {
103
141
  console.log(` Estimated cost: ${monthly}.`)
104
142
  const ok = yes || (interactive && (await ask('Proceed with the deploy?')))
105
143
  if (!ok) { console.log('Aborted.'); return null }
106
- res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes: { ...attributes, confirmCost: true } } }, flags)
144
+ res = await create({ data: { type: 'deployments', attributes: { ...attributes, confirmCost: true } } })
107
145
  }
108
146
 
109
147
  const dep = res.data || {}
@@ -0,0 +1,58 @@
1
+ // `saaslayer env export --binding <bindingId> [--format dotenv|json]`: a consumer binding's public discovery fields as
2
+ // environment variables, to bake into an app at build or deploy time. Anonymous: no credentials are read or sent.
3
+ 'use strict'
4
+ const { discoverDeployment, loadDiscovery } = require('../discovery')
5
+ const { bindingDiscoveryUrl } = require('./bindings')
6
+
7
+ const FORMATS = ['dotenv', 'json']
8
+
9
+ /**
10
+ * A fetch that keeps the last response body it read, so the binding's `meta` and the server's problem stay available
11
+ * after discovery decodes the document.
12
+ * @param {typeof fetch} doFetch
13
+ */
14
+ function bodyKeepingFetch(doFetch) {
15
+ /** @type {{ body: any }} */
16
+ const seen = { body: null }
17
+ /** @type {typeof fetch} */
18
+ const wrapped = async (url, init) => {
19
+ const res = await doFetch(url, init)
20
+ let body = null
21
+ try { body = await res.json() } catch { body = null }
22
+ seen.body = body
23
+ return /** @type {Response} */ ({ ok: res.ok, status: res.status, json: async () => body })
24
+ }
25
+ return { fetch: wrapped, seen }
26
+ }
27
+
28
+ /**
29
+ * Print a consumer binding's env block (dotenv by default, or one JSON object) on stdout; a handoff underway is a
30
+ * notice on stderr so stdout stays the env block alone.
31
+ * @param {Record<string, any>} flags
32
+ * @param {{ fetch?: typeof fetch }} [deps]
33
+ * @returns {Promise<Record<string, string>>}
34
+ */
35
+ async function envExport(flags, { fetch: doFetch = globalThis.fetch } = {}) {
36
+ const bindingId = flags.binding
37
+ if (!bindingId || typeof bindingId !== 'string') throw new Error('--binding <bindingId> is required')
38
+ const format = flags.format === undefined ? 'dotenv' : flags.format
39
+ if (!FORMATS.includes(format)) throw new Error('--format must be dotenv or json')
40
+ const { fetch: keeping, seen } = bodyKeepingFetch(doFetch)
41
+ /** @type {import('../../../discovery/src/index.mjs').DeploymentDiscovery} */
42
+ let doc
43
+ try {
44
+ doc = await discoverDeployment({ url: bindingDiscoveryUrl(flags, bindingId) }, { fetch: keeping })
45
+ } catch (err) {
46
+ const problem = Array.isArray(seen.body?.errors) ? seen.body.errors[0] : null
47
+ if (problem?.code) throw new Error(`${problem.code}: ${problem.detail || problem.title}`)
48
+ throw err
49
+ }
50
+ const { discoveryEnv, discoveryDotenv } = await loadDiscovery()
51
+ const handoff = seen.body?.meta?.handoff
52
+ if (handoff) console.error(`notice: consumer binding ${bindingId} has a handoff to ${handoff.toDeploymentId} (state: ${handoff.state}); re-export once it completes`)
53
+ const env = discoveryEnv(doc)
54
+ console.log(format === 'json' ? JSON.stringify(env, null, 2) : discoveryDotenv(doc))
55
+ return env
56
+ }
57
+
58
+ module.exports = { envExport }
@@ -4,14 +4,17 @@
4
4
  const { apiCall } = require('../api-client')
5
5
  const { resolveDeployment } = require('../deployments')
6
6
  const { finishMutation, requestKeyHeaders } = require('./operations')
7
+ const { signInRefusalHint } = require('../login-methods')
7
8
 
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
+ // Mirrors the deployer's adminPhoneNumber rule (E.164).
10
+ const E164 = /^\+[1-9]\d{6,14}$/
11
+ const USAGE = 'usage: saaslayer first-admin <resend|recover> [--deployment ID | --project P --env E --region R] [--email E | --phone-number +E164] [--reason TEXT] [--suid ID] [--no-wait]'
9
12
 
10
13
  /**
11
14
  * The request attributes for a subcommand; refusals happen before anything is sent.
12
15
  * @param {string|undefined} sub
13
16
  * @param {Record<string, unknown>} flags
14
- * @returns {{ action: 'resend'|'recover', adminEmail?: string, adminSuid?: string, reason?: string }}
17
+ * @returns {{ action: 'resend'|'recover', adminEmail?: string, adminPhoneNumber?: string, adminSuid?: string, reason?: string }}
15
18
  */
16
19
  function requestOf(sub, flags) {
17
20
  /** @param {unknown} v */
@@ -20,10 +23,13 @@ function requestOf(sub, flags) {
20
23
  if (sub === 'resend') return { action: 'resend', ...(reason ? { reason } : {}) }
21
24
  if (sub !== 'recover') throw new Error(USAGE)
22
25
  const adminEmail = text(flags.email)
23
- if (!adminEmail) throw new Error('first-admin recover needs --email <new admin email>')
26
+ const adminPhoneNumber = text(flags['phone-number'])
27
+ if (adminEmail && adminPhoneNumber) throw new Error('first-admin recover names the new admin by --email or --phone-number, not both')
28
+ if (!adminEmail && !adminPhoneNumber) throw new Error('first-admin recover needs --email <new admin email> (or --phone-number <E.164> on a phone-primary deployment)')
29
+ if (adminPhoneNumber && !E164.test(adminPhoneNumber)) throw new Error('first-admin recover --phone-number must be in E.164 form, like +15555550100')
24
30
  if (!reason) throw new Error('first-admin recover needs --reason <text> (recorded in the deployment activity)')
25
31
  const adminSuid = text(flags.suid)
26
- return { action: 'recover', adminEmail, ...(adminSuid ? { adminSuid } : {}), reason }
32
+ return { action: 'recover', ...(adminEmail ? { adminEmail } : { adminPhoneNumber }), ...(adminSuid ? { adminSuid } : {}), reason }
27
33
  }
28
34
 
29
35
  /**
@@ -34,6 +40,11 @@ async function firstAdminCommand(sub, flags) {
34
40
  const attributes = requestOf(sub, flags)
35
41
  const deploymentId = typeof flags.deployment === 'string' ? flags.deployment : (await resolveDeployment(flags)).deploymentId
36
42
  const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/admin-bootstrap`, { data: { type: 'admin-bootstrap-requests', attributes } }, flags, { headers: requestKeyHeaders() })
43
+ .catch((err) => {
44
+ const hint = signInRefusalHint(err)
45
+ if (hint) err.message += `\n${hint}`
46
+ throw err
47
+ })
37
48
  const attrs = (res.data && res.data.attributes) || {}
38
49
  console.log(`first-admin ${attributes.action} started: operation ${attrs.operationId || '—'} on deployment ${deploymentId}`)
39
50
  return finishMutation({ response: res, deploymentId, flags })