saaslayer 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -16
- package/bin/saaslayer.js +321 -60
- package/package.json +3 -2
- package/src/aws-sigv4.js +74 -26
- package/src/commands/access-admins.js +2 -2
- package/src/commands/admin-allowlist.js +23 -3
- package/src/commands/api-keys.js +83 -0
- package/src/commands/audit.js +77 -0
- package/src/commands/aws.js +355 -82
- package/src/commands/binding-handoff.js +174 -0
- package/src/commands/bindings.js +111 -0
- package/src/commands/catalog.js +30 -3
- package/src/commands/deploy.js +33 -10
- package/src/commands/env-export.js +58 -0
- package/src/commands/first-admin.js +15 -4
- package/src/commands/foundation.js +75 -117
- package/src/commands/hooks.js +271 -0
- package/src/commands/integration-credentials.js +1 -1
- package/src/commands/lifecycle.js +149 -24
- package/src/commands/login-domain.js +259 -0
- package/src/commands/permission-orgs.js +80 -0
- package/src/commands/release-manifest.js +17 -8
- package/src/commands/service-principals.js +42 -5
- package/src/commands/settings.js +21 -5
- package/src/commands/sms-registration.js +182 -0
- package/src/commands/sms.js +178 -0
- package/src/commands/social.js +265 -0
- package/src/commands/support-staff.js +72 -0
- package/src/commands/users-management.js +2 -20
- package/src/commands/users.js +56 -11
- package/src/commands/versions.js +61 -0
- package/src/connection-proof.js +41 -0
- package/src/deployments.js +1 -1
- package/src/foundation-change-set.js +180 -0
- package/src/foundation-home.js +121 -0
- package/src/foundation-template.js +51 -10
- package/src/foundation-trust-write.js +379 -0
- package/src/iam-session.js +14 -8
- package/src/login-domain.js +139 -0
- package/src/login-methods.js +118 -0
- package/src/module-catalog.js +3 -2
- package/src/release-manifest.js +11 -4
- package/src/scope.js +3 -1
- package/src/settings.js +85 -13
- package/src/sms/number.js +37 -0
- package/src/sms/registration-fields.js +167 -0
- package/src/sms/registration-validate.js +151 -0
- package/src/sms/registration.js +216 -0
- package/src/sms/release.js +55 -0
- package/src/sms/scope.js +86 -0
- package/src/sms/status.js +181 -0
- package/src/ssm-api.js +31 -0
- package/src/trust-entries.js +350 -0
- package/src/user-service-instance.js +27 -0
- package/src/users-api.js +55 -8
- package/src/users-import/checkpoint.js +76 -0
- package/src/users-import/import.js +233 -24
- package/src/versions.js +80 -0
- package/templates/saaslayer-foundation-region.yml +45 -1
- package/templates/saaslayer-foundation.yml +747 -296
|
@@ -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 }
|
package/src/commands/catalog.js
CHANGED
|
@@ -149,10 +149,36 @@ async function catalogBootstrapOwner(positional, flags, deps = {}) {
|
|
|
149
149
|
}
|
|
150
150
|
|
|
151
151
|
/**
|
|
152
|
-
*
|
|
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 }
|
package/src/commands/deploy.js
CHANGED
|
@@ -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).
|
|
@@ -24,13 +26,19 @@ function selectedModules(flags) {
|
|
|
24
26
|
|
|
25
27
|
/**
|
|
26
28
|
* 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.
|
|
29
|
+
* release the catalog reports) and name the create-only ones. A --version or --channel names no commit here (versions
|
|
30
|
+
* carry none), so the control plane checks them, as it does when no revision is known.
|
|
28
31
|
* @param {Record<string, Record<string, unknown>>} parameters
|
|
29
|
-
* @param {
|
|
32
|
+
* @param {import('../versions').ReleaseChoice|null} choice
|
|
30
33
|
* @param {import('../module-catalog').CatalogModule[]} modules
|
|
31
34
|
* @param {object} flags
|
|
32
35
|
*/
|
|
33
|
-
async function checkCreateSettings(parameters,
|
|
36
|
+
async function checkCreateSettings(parameters, choice, modules, flags) {
|
|
37
|
+
if (choice && !('commitSha' in choice)) {
|
|
38
|
+
console.log(' settings for a version are checked by the control plane when it resolves the version')
|
|
39
|
+
return parameters
|
|
40
|
+
}
|
|
41
|
+
const commitSha = choice ? choice.commitSha : undefined
|
|
34
42
|
/** @param {string} id */
|
|
35
43
|
const revisionOf = (id) => commitSha || (modules.find((m) => m.id === id) || { attributes: {} }).attributes.revision
|
|
36
44
|
const ids = Object.keys(parameters)
|
|
@@ -58,9 +66,8 @@ async function deploy(flags, io = {}) {
|
|
|
58
66
|
const project = scope.project.value
|
|
59
67
|
const environment = scope.env.value
|
|
60
68
|
const services = selectedModules(flags)
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
const commitSha = flags['commit-sha'] || flags.commitSha
|
|
69
|
+
// The release to start on: --version, --channel or --commit-sha (none: the control plane's default, stable).
|
|
70
|
+
const choice = releaseChoice(flags)
|
|
64
71
|
// A settings file is input to this deploy; --set / --param values override it.
|
|
65
72
|
let parameters = mergePatches(typeof flags.settings === 'string' ? readSettingsFile(flags.settings) : undefined, parseSetFlags(flags.param, '--param'), parseSetFlags(flags.set, '--set'))
|
|
66
73
|
// Module ids, dependencies and --param module keys are checked against the catalog before anything is sent.
|
|
@@ -72,21 +79,31 @@ async function deploy(flags, io = {}) {
|
|
|
72
79
|
}
|
|
73
80
|
if (parameters) {
|
|
74
81
|
checkParamModules(parameters, modules)
|
|
75
|
-
parameters = await checkCreateSettings(parameters,
|
|
82
|
+
parameters = await checkCreateSettings(parameters, choice, modules, flags)
|
|
76
83
|
}
|
|
77
84
|
}
|
|
78
85
|
|
|
86
|
+
// The permanent primary and any added secondary: what they need is checked, and their preview shown, before anything is sent.
|
|
87
|
+
const adminPhoneNumber = typeof flags['admin-phone-number'] === 'string' ? flags['admin-phone-number'].trim() : undefined
|
|
88
|
+
const signIn = signInChange({ op: 'create', values: (parameters && parameters[USER_SERVICE]) || {}, adminPhoneNumber, env: environment })
|
|
89
|
+
if (signIn.problems.length) throw new Error(signIn.problems.join('\n'))
|
|
90
|
+
for (const line of signIn.preview) console.log(` ${line}`)
|
|
91
|
+
|
|
79
92
|
const attributes = {
|
|
80
93
|
customerId: project,
|
|
81
94
|
environment,
|
|
82
95
|
...(services ? { services } : {}),
|
|
83
96
|
...(flags.region ? { region: flags.region } : {}),
|
|
84
97
|
...(flags.target ? { targetAccountId: flags.target } : {}),
|
|
85
|
-
...(
|
|
98
|
+
...(choice || {}),
|
|
86
99
|
...(flags['admin-email'] ? { adminEmail: flags['admin-email'] } : {}),
|
|
100
|
+
...(adminPhoneNumber ? { adminPhoneNumber } : {}),
|
|
87
101
|
...(parameters ? { parameters } : {}),
|
|
88
102
|
}
|
|
89
103
|
|
|
104
|
+
// A version or channel the control plane doesn't know (or can't take) is refused before the create.
|
|
105
|
+
await checkReleaseChoice(choice, flags)
|
|
106
|
+
|
|
90
107
|
// Creating a deployment is never implicit: --yes, or a person confirms before the first create request is sent.
|
|
91
108
|
const what = `${services ? services.join(' + ') : 'the default services'} to ${project}/${environment}${flags.region ? '/' + flags.region : ''}`
|
|
92
109
|
if (!yes) {
|
|
@@ -94,7 +111,13 @@ async function deploy(flags, io = {}) {
|
|
|
94
111
|
if (!(await ask(`Create a deployment: ${what}${flags.target ? ` in account ${flags.target}` : ''}?`))) { console.log('Aborted.'); return null }
|
|
95
112
|
}
|
|
96
113
|
console.log(`Deploying ${what}…`)
|
|
97
|
-
|
|
114
|
+
/** @param {object} body */
|
|
115
|
+
const create = (body) => apiCall('POST', '/api/deployments', body, flags).catch((err) => {
|
|
116
|
+
const hint = signInRefusalHint(err, environment)
|
|
117
|
+
if (hint) err.message += `\n${hint}`
|
|
118
|
+
throw err
|
|
119
|
+
})
|
|
120
|
+
let res = await create({ data: { type: 'deployments', attributes } })
|
|
98
121
|
|
|
99
122
|
// Cost-confirm (D14): the BFF returns a deployment-estimate with status NEEDS_CONFIRMATION.
|
|
100
123
|
if (res.data && res.data.attributes && res.data.attributes.status === 'NEEDS_CONFIRMATION') {
|
|
@@ -103,7 +126,7 @@ async function deploy(flags, io = {}) {
|
|
|
103
126
|
console.log(` Estimated cost: ${monthly}.`)
|
|
104
127
|
const ok = yes || (interactive && (await ask('Proceed with the deploy?')))
|
|
105
128
|
if (!ok) { console.log('Aborted.'); return null }
|
|
106
|
-
res = await
|
|
129
|
+
res = await create({ data: { type: 'deployments', attributes: { ...attributes, confirmCost: true } } })
|
|
107
130
|
}
|
|
108
131
|
|
|
109
132
|
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
|
-
|
|
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
|
-
|
|
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 })
|