saaslayer 0.2.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 +132 -16
- package/bin/saaslayer.js +387 -61
- package/package.json +3 -2
- package/src/api-client.js +37 -1
- package/src/aws-sigv4.js +74 -26
- package/src/cognito-user-api.js +80 -0
- package/src/commands/access-admins.js +2 -2
- package/src/commands/account-email.js +43 -0
- package/src/commands/admin-allowlist.js +65 -0
- 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/login.js +53 -16
- package/src/commands/org-members.js +109 -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/trust-policies.js +172 -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/deployment-api-auth.js +166 -8
- 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/permissions-request.js +15 -9
- 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,178 @@
|
|
|
1
|
+
// `saaslayer sms setup|release` (cloud-prem): install the account's SMS sending number on the region foundation (toll-free,
|
|
2
|
+
// or dev-only simulator) and retire it as a resumable control-plane release (plan §3, §5); routes `sms register|status`.
|
|
3
|
+
'use strict'
|
|
4
|
+
const { execFileSync } = require('child_process')
|
|
5
|
+
const { jsonApiCall } = require('../api-client')
|
|
6
|
+
const { confirm: promptConfirm } = require('../prompt')
|
|
7
|
+
const { describeStack, applyRegionFoundation, waitForStack } = require('../foundation-change-set')
|
|
8
|
+
const { FOUNDATION_REGION_TEMPLATE, foundationRegionStackName } = require('./aws')
|
|
9
|
+
const { cloudPremTarget, smsReleasePath } = require('../sms/scope')
|
|
10
|
+
const { SMS_NUMBER_COST, smsNumberOf, logSmsNextSteps } = require('../sms/number')
|
|
11
|
+
const { isUnfinished, readRelease, advanceRelease, numberRemoved } = require('../sms/release')
|
|
12
|
+
const { createSmsClient, describeNumber, findRegistration, deleteRegistration } = require('../sms/registration')
|
|
13
|
+
|
|
14
|
+
/** @param {string} cmd @param {string[]} args */
|
|
15
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 })
|
|
16
|
+
const DEFAULT_WAIT = { sleep: (ms) => new Promise((r) => setTimeout(r, ms)), pollMs: 5000, maxPolls: 720 }
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {{ exec?: typeof defaultExec, api?: typeof jsonApiCall, confirm?: (q: string) => Promise<boolean>,
|
|
20
|
+
* log?: (...a: unknown[]) => void, wait?: import('../foundation-change-set').Wait,
|
|
21
|
+
* sms?: import('../sms/registration').SmsClient }} Deps
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** The region foundation stack of the target, refused when the account was never connected in that region. */
|
|
25
|
+
function regionStack(aws, target) {
|
|
26
|
+
const stack = describeStack(aws, foundationRegionStackName(target.region))
|
|
27
|
+
if (!stack) throw new Error(`${foundationRegionStackName(target.region)} is not installed in ${target.accountId}; connect the account in ${target.region} first: saaslayer aws connect --aws-account ${target.accountId} --region ${target.region}`)
|
|
28
|
+
return stack
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `saaslayer sms setup --env <env> [--region R] [--simulator] [--yes]`: install the toll-free (or, dev only, simulator)
|
|
33
|
+
* sending number on the region foundation of the env's account and region. Returns null when the prompt is declined.
|
|
34
|
+
* @param {object} flags @param {Deps} [deps]
|
|
35
|
+
*/
|
|
36
|
+
async function smsSetup(flags, { exec = defaultExec, api = jsonApiCall, confirm = promptConfirm, log = console.log, wait = DEFAULT_WAIT } = {}) {
|
|
37
|
+
const simulator = flags.simulator === true
|
|
38
|
+
const numberType = simulator ? 'simulator' : 'toll-free'
|
|
39
|
+
const { target, aws } = await cloudPremTarget(flags, 'sms setup', { api, exec })
|
|
40
|
+
if (simulator && target.env !== 'dev') throw new Error(`--simulator is for dev only (plan §5a); --env is ${target.env}`)
|
|
41
|
+
if (simulator && target.protectedDeployments) {
|
|
42
|
+
throw new Error(`--simulator refused: ${target.accountId} has staging or prod deployments; a simulator number belongs in a dev or test account`)
|
|
43
|
+
}
|
|
44
|
+
const stackName = foundationRegionStackName(target.region)
|
|
45
|
+
const installed = smsNumberOf(regionStack(aws, target))
|
|
46
|
+
if (installed.numberType === numberType && installed.arn) {
|
|
47
|
+
log(`${target.accountId} ${target.region} already has a ${numberType} SMS number.`)
|
|
48
|
+
logSmsNextSteps(log, { arn: installed.arn, env: target.env, numberType })
|
|
49
|
+
return { arn: installed.arn, numberType, accountId: target.accountId, region: target.region, changed: false }
|
|
50
|
+
}
|
|
51
|
+
if (installed.numberType !== 'none') {
|
|
52
|
+
throw new Error(`${target.accountId} ${target.region} already has a ${installed.numberType} SMS number (one per account and region); to replace it: saaslayer sms release --env ${target.env} first, then saaslayer sms setup`)
|
|
53
|
+
}
|
|
54
|
+
const release = await readRelease(api, target, flags)
|
|
55
|
+
if (release && isUnfinished(release.phase)) {
|
|
56
|
+
throw new Error(`an SMS release of ${release.phoneNumberArn} is ${release.phase}; finish it first: saaslayer sms release --env ${target.env}`)
|
|
57
|
+
}
|
|
58
|
+
if (release && release.phase === 'done' && !simulator) {
|
|
59
|
+
log(`A number was released here before: setting SMS up again buys a new number and needs a new registration (AWS review: up to 15 business days).`)
|
|
60
|
+
}
|
|
61
|
+
const what = simulator ? 'a simulator number (dev testing only, sends to AWS simulator destinations)' : 'a US toll-free number'
|
|
62
|
+
log(`This installs ${what} in ${target.accountId} ${target.region} through ${stackName}.`)
|
|
63
|
+
if (!flags.yes && !(await confirm(`AWS bills the number ${SMS_NUMBER_COST} to ${target.accountId} while it exists. Install it?`))) {
|
|
64
|
+
log('Nothing changed.')
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
await applyRegionFoundation({ aws, stackName, templateFile: FOUNDATION_REGION_TEMPLATE, overrides: { SmsOriginationNumberType: numberType }, wait, log })
|
|
68
|
+
const { arn } = smsNumberOf(regionStack(aws, target))
|
|
69
|
+
if (!arn) throw new Error(`${stackName} updated but reports no SmsOriginationIdentityArn; check the stack in the CloudFormation console`)
|
|
70
|
+
logSmsNextSteps(log, { arn, env: target.env, numberType })
|
|
71
|
+
return { arn, numberType, accountId: target.accountId, region: target.region, changed: true }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Waits out an in-progress stack operation, then returns the stack. */
|
|
75
|
+
async function settledStack(aws, target, wait) {
|
|
76
|
+
const stack = regionStack(aws, target)
|
|
77
|
+
if (!/_IN_PROGRESS$/.test(stack.StackStatus)) return stack
|
|
78
|
+
try { await waitForStack(aws, stack.StackName || foundationRegionStackName(target.region), 'UPDATE', wait) } catch { /* its final state is read below */ }
|
|
79
|
+
return regionStack(aws, target)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* `saaslayer sms release --env <env> [--yes]` (plan §5): lock and record first, reference check under the lock, confirm,
|
|
84
|
+
* release the number (parameter -> none), then delete its registration. Every step is recorded in the control plane, so a
|
|
85
|
+
* re-run from any machine resumes from the recorded phase; the lock is kept while CloudFormation's outcome is uncertain.
|
|
86
|
+
* @param {object} flags @param {Deps} [deps]
|
|
87
|
+
*/
|
|
88
|
+
async function smsRelease(flags, { exec = defaultExec, api = jsonApiCall, confirm = promptConfirm, log = console.log, wait = DEFAULT_WAIT, sms } = {}) {
|
|
89
|
+
const { target, aws } = await cloudPremTarget(flags, 'sms release', { api, exec })
|
|
90
|
+
const client = sms || createSmsClient({ region: target.region, profile: flags.profile })
|
|
91
|
+
const path = smsReleasePath(target)
|
|
92
|
+
const advance = (from, phase) => advanceRelease(api, target, flags, from, phase)
|
|
93
|
+
|
|
94
|
+
let record = await readRelease(api, target, flags)
|
|
95
|
+
if (record && isUnfinished(record.phase)) {
|
|
96
|
+
log(`Resuming the SMS release of ${record.phoneNumberArn} (${record.phase}).`)
|
|
97
|
+
} else {
|
|
98
|
+
const number = smsNumberOf(regionStack(aws, target))
|
|
99
|
+
if (!number.arn) {
|
|
100
|
+
log(`${target.accountId} ${target.region} has no SMS number; nothing to release.`)
|
|
101
|
+
return { phase: null }
|
|
102
|
+
}
|
|
103
|
+
// The number's registration: the one AWS associated with it, else the live one tagged for it (plan §4 step 1).
|
|
104
|
+
const registration = number.numberType === 'simulator' ? null : (await findRegistration(client, await describeNumber(client, number.arn))).registration
|
|
105
|
+
const registrationId = registration ? registration.RegistrationId : null
|
|
106
|
+
record = (await api('POST', path, { data: { type: 'sms-releases', attributes: { phoneNumberId: number.phoneNumberId, phoneNumberArn: number.arn, registrationId, numberType: number.numberType } } }, flags)).data.attributes
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (record.phase === 'checking') {
|
|
110
|
+
if (!record.referenceCheckedAt) {
|
|
111
|
+
try {
|
|
112
|
+
record = (await api('POST', `${path}/reference-check`, undefined, flags)).data.attributes
|
|
113
|
+
} catch (err) {
|
|
114
|
+
const first = err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
|
|
115
|
+
if (first && first.code === 'SMS_ORIGINATION_IN_USE') {
|
|
116
|
+
const { references = [], otherReferences = 0 } = first.meta || {}
|
|
117
|
+
log(`Release refused: deployments still use ${record.phoneNumberArn}.`)
|
|
118
|
+
for (const r of references) log(` ${r.deploymentId} project ${r.customerId || '—'} env ${r.environment || '—'} ${r.services.join(', ')}${r.inFlight ? ' (run in flight)' : ''}`)
|
|
119
|
+
if (otherReferences) log(` and ${otherReferences} in projects you cannot see`)
|
|
120
|
+
throw new Error('point those deployments at another number (or remove PhoneSmsOriginationIdentity) first; nothing was released')
|
|
121
|
+
}
|
|
122
|
+
// Fail closed: nothing is released. Drop the lock if the control plane answers; a re-run starts over otherwise.
|
|
123
|
+
await advance('checking', 'refused').catch(() => {})
|
|
124
|
+
throw new Error(`the reference check could not complete (${err.message}); nothing was released`)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const loses = record.registrationId ? `its registration ${record.registrationId} (approved or not) is deleted, and ` : ''
|
|
128
|
+
log(`Releasing ${record.phoneNumberArn} (${record.numberType}) in ${target.accountId} ${target.region}: AWS deletes the number, ${loses}a new number needs a new registration (AWS review: up to 15 business days).`)
|
|
129
|
+
if (!flags.yes && !(await confirm('Release this number?'))) {
|
|
130
|
+
await advance('checking', 'refused')
|
|
131
|
+
log('Nothing released.')
|
|
132
|
+
return { phase: 'refused' }
|
|
133
|
+
}
|
|
134
|
+
record = await advance('checking', 'releasing-number')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (record.phase === 'releasing-number') {
|
|
138
|
+
const stack = await settledStack(aws, target, wait)
|
|
139
|
+
if (!numberRemoved(stack)) {
|
|
140
|
+
const stackName = foundationRegionStackName(target.region)
|
|
141
|
+
try {
|
|
142
|
+
await applyRegionFoundation({ aws, stackName, templateFile: FOUNDATION_REGION_TEMPLATE, overrides: { SmsOriginationNumberType: 'none' }, wait, log, allowSmsNumberRemoval: true })
|
|
143
|
+
} catch (err) {
|
|
144
|
+
throw new Error(`the number release did not finish (${err.message}); the release keeps its lock. Re-run saaslayer sms release --env ${target.env} (from any machine) once ${stackName} has settled`)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
record = await advance('releasing-number', 'number-released')
|
|
148
|
+
log(`Number released: ${record.phoneNumberArn} is deleted and no longer billed.`)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (record.phase === 'number-released') {
|
|
152
|
+
record = await advance('number-released', record.registrationId ? 'deleting-registration' : 'done')
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (record.phase === 'deleting-registration') {
|
|
156
|
+
try {
|
|
157
|
+
await deleteRegistration(client, record.registrationId)
|
|
158
|
+
} catch (err) {
|
|
159
|
+
throw new Error(`number released, registration cleanup pending: deleting ${record.registrationId} failed (${err.message}). Re-run saaslayer sms release --env ${target.env} (from any machine) to finish`)
|
|
160
|
+
}
|
|
161
|
+
record = await advance('deleting-registration', 'done')
|
|
162
|
+
log(`Registration ${record.registrationId} deleted.`)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (record.phase === 'done') log(`SMS release done; the lock on ${target.accountId} ${target.region} is dropped. To send again: saaslayer sms setup --env ${target.env} (a new number and registration).`)
|
|
166
|
+
return { phase: record.phase }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** @param {string} sub @param {object} flags */
|
|
170
|
+
async function smsCommand(sub, flags) {
|
|
171
|
+
if (sub === 'setup') return smsSetup(flags)
|
|
172
|
+
if (sub === 'release') return smsRelease(flags)
|
|
173
|
+
if (sub === 'register') return require('./sms-registration').smsRegister(flags)
|
|
174
|
+
if (sub === 'status') return require('./sms-registration').smsStatus(flags)
|
|
175
|
+
throw new Error('usage: saaslayer sms <setup|register|status|release> --env <env> [--region R] (see saaslayer --help)')
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
module.exports = { smsSetup, smsRelease, smsCommand }
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// `saaslayer social status|enable|rotate-secret|disable <provider>`: read one user-service instance's social sign-in
|
|
2
|
+
// settings, or change them as ONE social configuration (POST /api/deployments/{id}/social), then wait for its run.
|
|
3
|
+
'use strict'
|
|
4
|
+
const crypto = require('crypto')
|
|
5
|
+
const { apiCall } = require('../api-client')
|
|
6
|
+
const { resolveDeployment } = require('../deployments')
|
|
7
|
+
const { finishMutation, resumeCommand } = require('./operations')
|
|
8
|
+
const { PROTECTED_ENVS } = require('../settings')
|
|
9
|
+
const { chooseInstance, refOf } = require('../user-service-instance')
|
|
10
|
+
const { redirectUrisOf } = require('./login-domain')
|
|
11
|
+
|
|
12
|
+
const USAGE = 'usage: saaslayer social <status|enable|rotate-secret|disable> [google] [--env E] [--service REF] … (see saaslayer --help)'
|
|
13
|
+
// The providers this command configures, with the setting-name prefix their settings carry.
|
|
14
|
+
const PROVIDERS = { google: { name: 'Google', prefix: 'Google' } }
|
|
15
|
+
// Transient answers a request is sent again for, with the same request key: the deployer answers the same run.
|
|
16
|
+
const RETRIED_STATUSES = new Set([502, 504])
|
|
17
|
+
const ATTEMPTS = 3
|
|
18
|
+
// Login-domain states in which the custom host serves sign-in, so its redirect URI must be registered too.
|
|
19
|
+
const SERVING_LOGIN_DOMAIN_STATES = new Set(['provisioning', 'provisioned', 'active', 'deactivating'])
|
|
20
|
+
|
|
21
|
+
/** @param {unknown} value a CSV setting @returns {string[]} */
|
|
22
|
+
const csv = (value) => (typeof value === 'string' ? value.split(',').map((s) => s.trim()).filter(Boolean) : [])
|
|
23
|
+
/** @param {unknown} value a repeatable flag @returns {string[]|undefined} */
|
|
24
|
+
const list = (value) => (value === undefined ? undefined : (Array.isArray(value) ? value : [value]).map(String))
|
|
25
|
+
/** @param {unknown} value a boolean-ish setting */
|
|
26
|
+
const truthy = (value) => value === true || value === 'true'
|
|
27
|
+
|
|
28
|
+
/** A login host from a Cognito domain output: a custom host as is, a prefix domain in the region. @param {unknown} domain @param {string|undefined} region */
|
|
29
|
+
const cognitoHost = (domain, region) => (domain ? (String(domain).includes('.') ? String(domain) : `${domain}.auth.${region || 'us-east-1'}.amazoncognito.com`) : null)
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The redirect URIs a provider console needs for an instance, labelled: the advertised host's (active), then any other
|
|
33
|
+
* host that serves sign-in (a pending custom domain, the opaque prefix domain).
|
|
34
|
+
* @param {Record<string, any>} instance @param {string|undefined} region
|
|
35
|
+
* @param {Record<string, any>|null} loginDomain the instance's login-domain status, when the control plane has one
|
|
36
|
+
*/
|
|
37
|
+
function labelledRedirectUris(instance, region, loginDomain) {
|
|
38
|
+
const outputs = instance.outputs || {}
|
|
39
|
+
const pending = loginDomain && SERVING_LOGIN_DOMAIN_STATES.has(loginDomain.state) ? loginDomain.host : null
|
|
40
|
+
return redirectUrisOf({ activeHost: cognitoHost(outputs.UserPoolDomainName, region), host: pending, opaqueHost: cognitoHost(outputs.OpaqueLoginDomainName, region) })
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The callback URLs registered in only one trailing-slash form, each with the form that is missing. The sign-in widget
|
|
45
|
+
* returns to `origin + pathname` of its page, so a bare origin is always sent as `origin/`; a file-like path or a URL
|
|
46
|
+
* with a query or fragment has no other form a site serves.
|
|
47
|
+
* @param {string[]} urls @returns {Array<{ url: string, twin: string }>}
|
|
48
|
+
*/
|
|
49
|
+
function slashTwinsMissing(urls) {
|
|
50
|
+
const registered = new Set(urls)
|
|
51
|
+
return urls.flatMap((url) => {
|
|
52
|
+
let parsed
|
|
53
|
+
try { parsed = new URL(url) } catch { return [] }
|
|
54
|
+
if (parsed.search || parsed.hash || /\.[A-Za-z0-9]+$/.test(parsed.pathname)) return []
|
|
55
|
+
if (parsed.pathname === '/' && url.endsWith('/')) return []
|
|
56
|
+
const twin = url.endsWith('/') ? url.slice(0, -1) : `${url}/`
|
|
57
|
+
return registered.has(twin) ? [] : [{ url, twin }]
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const SLASH_WARNING = ' warning: the sign-in widget returns to the exact address of its page, and Cognito refuses a callback URL that is not registered character for character ("RedirectUri is not registered with the client", shown only after the provider\'s sign-in). Register each page at the address the site serves it, trailing slash included:'
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* What the instance's settings say about social sign-in, and the values its provider console needs.
|
|
65
|
+
* @param {string} deploymentId
|
|
66
|
+
* @param {string|undefined} region
|
|
67
|
+
* @param {Record<string, any>} instance the instance's module in the deployment detail (its ref and outputs)
|
|
68
|
+
* @param {Record<string, unknown>} params the instance's setting values, as `settings get` reads them
|
|
69
|
+
* @param {Array<{ uri: string }>} redirectUris every redirect URI to register, the advertised host's first
|
|
70
|
+
*/
|
|
71
|
+
function statusOf(deploymentId, region, instance, params, redirectUris = []) {
|
|
72
|
+
const host = cognitoHost((instance.outputs || {}).UserPoolDomainName, region)
|
|
73
|
+
const providers = Object.fromEntries(Object.entries(PROVIDERS).map(([provider, { prefix }]) => [provider, {
|
|
74
|
+
enabled: truthy(params[`Enable${prefix}Login`]),
|
|
75
|
+
clientId: typeof params[`${prefix}ClientId`] === 'string' && params[`${prefix}ClientId`] ? params[`${prefix}ClientId`] : null,
|
|
76
|
+
hostedDomains: csv(params[`${prefix}HostedDomains`]),
|
|
77
|
+
}]))
|
|
78
|
+
return {
|
|
79
|
+
deploymentId,
|
|
80
|
+
service: refOf(/** @type {any} */ (instance)),
|
|
81
|
+
providers,
|
|
82
|
+
callbackUrls: csv(params.AllowedCallbackUrls),
|
|
83
|
+
logoutUrls: csv(params.AllowedLogoutUrls),
|
|
84
|
+
appOrigins: csv(params.AllowedAppOrigins),
|
|
85
|
+
redirectUri: host ? `https://${host}/oauth2/idpresponse` : null,
|
|
86
|
+
authOrigin: host ? `https://${host}` : null,
|
|
87
|
+
redirectUris: redirectUris.map(({ uri }) => uri),
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* @param {ReturnType<typeof statusOf>} status @param {string|undefined} region
|
|
93
|
+
* @param {Array<{ uri: string, label: string }>} [others] the redirect URIs besides the advertised host's
|
|
94
|
+
*/
|
|
95
|
+
function formatStatus(status, region, others = []) {
|
|
96
|
+
const shown = (items) => (items.length ? items.join(', ') : '—')
|
|
97
|
+
const lines = [`${status.service} on deployment ${status.deploymentId} (${region})`]
|
|
98
|
+
for (const [provider, p] of Object.entries(status.providers)) {
|
|
99
|
+
lines.push(` ${provider}: ${p.enabled ? 'enabled' : 'disabled'}`, ` client id: ${p.clientId || '—'}`, ` hosted domains: ${shown(p.hostedDomains)}`)
|
|
100
|
+
}
|
|
101
|
+
lines.push(` callback URLs: ${shown(status.callbackUrls)}`)
|
|
102
|
+
const missing = slashTwinsMissing(status.callbackUrls)
|
|
103
|
+
if (missing.length) lines.push(SLASH_WARNING, ...missing.map(({ url, twin }) => ` ${url} is registered, ${twin} is not`))
|
|
104
|
+
lines.push(` logout URLs: ${shown(status.logoutUrls)}`, ` app origins: ${shown(status.appOrigins)}`)
|
|
105
|
+
if (status.redirectUri) {
|
|
106
|
+
lines.push(' Google console (APIs & Services -> Credentials):', ` Authorized redirect URI: ${status.redirectUri}`, ` Authorized JavaScript origin: ${status.authOrigin}`)
|
|
107
|
+
lines.push(...others.map(({ uri, label }) => ` also keep registered (${label}): ${uri}`))
|
|
108
|
+
}
|
|
109
|
+
else lines.push(' redirect URI unavailable: deploy this user-service instance first so its Cognito domain exists')
|
|
110
|
+
return lines
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The deployment, its chosen instance and that instance's social status.
|
|
115
|
+
* @param {Record<string, any>} flags
|
|
116
|
+
*/
|
|
117
|
+
async function readStatus(flags) {
|
|
118
|
+
const deployment = await resolveDeployment(flags)
|
|
119
|
+
const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}`, undefined, flags)
|
|
120
|
+
const detail = { deploymentId: deployment.deploymentId, ...doc.data.attributes }
|
|
121
|
+
const instance = chooseInstance(detail, flags)
|
|
122
|
+
const settingsDoc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, undefined, flags)
|
|
123
|
+
const settings = (settingsDoc.data.attributes.modules || []).find((m) => m.ref === refOf(instance))
|
|
124
|
+
const params = Object.fromEntries(((settings && settings.settings) || []).map((s) => [s.name, s.value]))
|
|
125
|
+
const region = detail.region || deployment.region
|
|
126
|
+
const redirectUris = labelledRedirectUris(instance, region, await readLoginDomain(deployment.deploymentId, refOf(instance), flags))
|
|
127
|
+
const others = redirectUris.filter(({ label }) => label !== 'active')
|
|
128
|
+
return { deployment, region, others, status: statusOf(deployment.deploymentId, region, instance, params, redirectUris) }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The instance's login-domain status, or null where the control plane has no login-domain route (404).
|
|
133
|
+
* @param {string} deploymentId @param {string} ref @param {Record<string, any>} flags
|
|
134
|
+
*/
|
|
135
|
+
async function readLoginDomain(deploymentId, ref, flags) {
|
|
136
|
+
try {
|
|
137
|
+
const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}/services/${encodeURIComponent(ref)}/login-domain`, undefined, flags)
|
|
138
|
+
return doc.data.attributes
|
|
139
|
+
} catch (err) {
|
|
140
|
+
if (err && err.status === 404) return null
|
|
141
|
+
throw err
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The client secret piped on stdin (one trailing newline dropped). A terminal stdin is refused: the secret is never
|
|
147
|
+
* typed where it could echo, and never taken from a flag or the environment.
|
|
148
|
+
* @param {string} sub @param {NodeJS.ReadableStream & { isTTY?: boolean }} stdin
|
|
149
|
+
*/
|
|
150
|
+
async function readSecret(sub, stdin) {
|
|
151
|
+
if (stdin.isTTY) throw new Error(`--client-secret-stdin reads the secret from a pipe or file, e.g. saaslayer social ${sub} google --client-secret-stdin < secret.txt`)
|
|
152
|
+
let data = ''
|
|
153
|
+
for await (const chunk of stdin) data += chunk
|
|
154
|
+
const secret = data.replace(/\r?\n$/, '')
|
|
155
|
+
if (!secret) throw new Error('the client secret on stdin is empty')
|
|
156
|
+
return secret
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Send one social configuration, retrying a dropped connection with the same request and request key.
|
|
161
|
+
* @param {string} deploymentId @param {object} attributes @param {Record<string, any>} flags @param {{ retryDelayMs: number }} opts
|
|
162
|
+
*/
|
|
163
|
+
async function sendConfiguration(deploymentId, attributes, flags, { retryDelayMs }) {
|
|
164
|
+
const body = { data: { type: 'social-configurations', attributes }, meta: { idempotencyKey: `cli-${crypto.randomUUID()}` } }
|
|
165
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
166
|
+
try {
|
|
167
|
+
return await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/social`, body, flags)
|
|
168
|
+
} catch (err) {
|
|
169
|
+
const transient = err.status === undefined || RETRIED_STATUSES.has(err.status)
|
|
170
|
+
if (!transient || attempt >= ATTEMPTS) throw err
|
|
171
|
+
await new Promise((resolve) => setTimeout(resolve, retryDelayMs * attempt))
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* A refusal as `<code>: <title>` plus the next step it needs; with --json the refusal document is printed as is.
|
|
178
|
+
* @param {any} err @param {Record<string, any>} flags
|
|
179
|
+
*/
|
|
180
|
+
function refusalOf(err, flags) {
|
|
181
|
+
const first = err && err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
|
|
182
|
+
if (!first) return err
|
|
183
|
+
if (flags.json) console.log(JSON.stringify({ errors: err.body.errors }, null, 2))
|
|
184
|
+
let message = `${first.code || err.status}: ${first.title || first.detail || 'request refused'}`
|
|
185
|
+
if (first.code === 'SOCIAL_ONLY_USERS_AFFECTED') message += '\neach of them needs another sign-in method first (a signed-in user can add a password from their profile); `saaslayer social status` shows the instance'
|
|
186
|
+
return Object.assign(new Error(message), { status: err.status, body: err.body })
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The provider attributes for a change; refusals happen before anything is sent.
|
|
191
|
+
* @param {'enable'|'rotate-secret'|'disable'} sub @param {string} provider @param {ReturnType<typeof statusOf>} status
|
|
192
|
+
* @param {Record<string, any>} flags @param {{ stdin: NodeJS.ReadableStream }} deps
|
|
193
|
+
*/
|
|
194
|
+
async function providerChange(sub, provider, status, flags, deps) {
|
|
195
|
+
const current = status.providers[provider]
|
|
196
|
+
if (sub === 'disable') return { enabled: false }
|
|
197
|
+
if (sub === 'rotate-secret' && !flags['client-secret-stdin']) throw new Error(`social rotate-secret ${provider} needs --client-secret-stdin`)
|
|
198
|
+
if (sub === 'rotate-secret' && !current.enabled) throw new Error(`${provider} is off on ${status.service}: enable it with saaslayer social enable ${provider}`)
|
|
199
|
+
const clientId = typeof flags['client-id'] === 'string' ? flags['client-id'] : current.clientId
|
|
200
|
+
if (!clientId) throw new Error(`social enable ${provider} needs --client-id <id>: ${status.service} has no ${PROVIDERS[provider].name} client id yet`)
|
|
201
|
+
const clientSecret = flags['client-secret-stdin'] ? await readSecret(sub, deps.stdin) : undefined
|
|
202
|
+
const hostedDomains = sub === 'enable' ? list(flags['hosted-domain']) : undefined
|
|
203
|
+
return { enabled: true, clientId, ...(clientSecret ? { clientSecret } : {}), ...(hostedDomains ? { hostedDomains } : {}) }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const DONE = { enable: 'enabled', 'rotate-secret': 'client secret rotated', disable: 'disabled' }
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* `social enable|rotate-secret|disable <provider>`: one social configuration for the chosen instance, then its run.
|
|
210
|
+
* @param {'enable'|'rotate-secret'|'disable'} sub @param {string|undefined} provider @param {Record<string, any>} flags
|
|
211
|
+
* @param {{ stdin: NodeJS.ReadableStream, retryDelayMs: number }} deps
|
|
212
|
+
*/
|
|
213
|
+
async function changeSocial(sub, provider, flags, deps) {
|
|
214
|
+
if (!provider) throw new Error(`social ${sub} needs a provider: ${Object.keys(PROVIDERS).join(', ')}`)
|
|
215
|
+
if (!PROVIDERS[provider]) throw new Error(`${provider} cannot be configured here: ${Object.keys(PROVIDERS).join(', ')} is the only provider so far`)
|
|
216
|
+
if (flags['client-secret'] !== undefined) throw new Error('pass the client secret on stdin with --client-secret-stdin (never as a flag)')
|
|
217
|
+
const { deployment, status } = await readStatus(flags)
|
|
218
|
+
const reason = typeof flags.reason === 'string' && flags.reason.trim() ? flags.reason.trim() : undefined
|
|
219
|
+
if (!reason && PROTECTED_ENVS.has(deployment.env)) throw new Error(`${deployment.env} is a protected environment: pass --reason <text>`)
|
|
220
|
+
const change = await providerChange(sub, provider, status, flags, deps)
|
|
221
|
+
const callbackUrls = sub === 'enable' ? list(flags['callback-url']) : undefined
|
|
222
|
+
const appOrigins = sub === 'enable' ? list(flags['app-origin']) : undefined
|
|
223
|
+
const attributes = {
|
|
224
|
+
service: status.service,
|
|
225
|
+
providers: { [provider]: change },
|
|
226
|
+
...(callbackUrls ? { callbackUrls } : {}),
|
|
227
|
+
...(appOrigins ? { appOrigins } : {}),
|
|
228
|
+
...(reason ? { reason } : {}),
|
|
229
|
+
...(sub === 'disable' && flags.confirm === true ? { confirm: true } : {}),
|
|
230
|
+
}
|
|
231
|
+
let res
|
|
232
|
+
try {
|
|
233
|
+
res = await sendConfiguration(deployment.deploymentId, attributes, flags, deps)
|
|
234
|
+
} catch (err) {
|
|
235
|
+
throw refusalOf(err, flags)
|
|
236
|
+
}
|
|
237
|
+
const answered = res.data.attributes
|
|
238
|
+
// Without an operation there is nothing to wait on, so success cannot be reported.
|
|
239
|
+
if (typeof answered.operationId !== 'string' || !answered.operationId) {
|
|
240
|
+
const follow = answered.runId ? `: follow its run with \`${resumeCommand(answered.runId, deployment.deploymentId)}\`` : ''
|
|
241
|
+
throw new Error(`the control plane accepted the change but named no operation to wait on (run ${answered.runId || 'unknown'})${follow}`)
|
|
242
|
+
}
|
|
243
|
+
const revision = answered.secretRevisions && answered.secretRevisions[provider]
|
|
244
|
+
console.log(`${provider} ${DONE[sub]} on ${status.service} of ${deployment.deploymentId}: operation ${answered.operationId}${revision ? `, client secret stored as revision ${revision}` : ''}`)
|
|
245
|
+
return finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* @param {string|undefined} sub status | enable | rotate-secret | disable
|
|
250
|
+
* @param {string|undefined} provider
|
|
251
|
+
* @param {Record<string, any>} flags
|
|
252
|
+
* @param {{ stdin?: NodeJS.ReadableStream, retryDelayMs?: number }} [deps]
|
|
253
|
+
*/
|
|
254
|
+
async function socialCommand(sub, provider, flags, deps = {}) {
|
|
255
|
+
const resolved = { stdin: deps.stdin || process.stdin, retryDelayMs: deps.retryDelayMs === undefined ? 1000 : deps.retryDelayMs }
|
|
256
|
+
if (sub === 'status') {
|
|
257
|
+
const { region, status, others } = await readStatus(flags)
|
|
258
|
+
console.log(flags.json ? JSON.stringify(status, null, 2) : formatStatus(status, region, others).join('\n'))
|
|
259
|
+
return status
|
|
260
|
+
}
|
|
261
|
+
if (sub === 'enable' || sub === 'rotate-secret' || sub === 'disable') return changeSocial(sub, provider, flags, resolved)
|
|
262
|
+
throw new Error(USAGE)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
module.exports = { socialCommand }
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// `saaslayer permissions support-staff grant|revoke|list`: the deployment's support staff, who view as members of any org
|
|
2
|
+
// through the reserved support roles (view-only or act-as), granted and revoked at deployment scope by an access admin in person.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
const { permissionsRequest } = require('../permissions-request')
|
|
7
|
+
|
|
8
|
+
// The reserved role ids: monorepo source first (vendor/ is a prepack snapshot), else the published copy.
|
|
9
|
+
const MONOREPO_DELEGATION = path.join(__dirname, '../../../permissions-engine-core/src/delegation.js')
|
|
10
|
+
const VENDORED_DELEGATION = path.join(__dirname, '../../vendor/permissions-engine-core/delegation.js')
|
|
11
|
+
/** @type {typeof import('../../../permissions-engine-core/src/delegation.js')} */
|
|
12
|
+
const { RESERVED_ROLES } = require(fs.existsSync(MONOREPO_DELEGATION) ? MONOREPO_DELEGATION : VENDORED_DELEGATION)
|
|
13
|
+
|
|
14
|
+
/** The reserved support role for each impersonation mode it allows at most. */
|
|
15
|
+
const ROLE_BY_MODE = Object.freeze({ 'view-only': RESERVED_ROLES.supportViewOnly.id, 'act-as': RESERVED_ROLES.supportActAs.id })
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {import('../permissions-request').PermissionsFlags & { mode?: string, 'expires-at'?: string }} SupportFlags
|
|
19
|
+
* @typedef {import('../permissions-request').Deps} Deps
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** @param {string} label @param {string[]} positional */
|
|
23
|
+
function suidOf(label, positional) {
|
|
24
|
+
if (!positional[0]) throw new Error(`${label}: <suid> is required`)
|
|
25
|
+
return positional[0]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @param {string} label @param {SupportFlags} flags */
|
|
29
|
+
function roleOf(label, flags) {
|
|
30
|
+
const roleId = flags.mode ? ROLE_BY_MODE[/** @type {keyof typeof ROLE_BY_MODE} */ (flags.mode)] : undefined
|
|
31
|
+
if (!roleId) throw new Error(`${label}: --mode view-only|act-as is required`)
|
|
32
|
+
return roleId
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Grant <suid> the support role for --mode (act-as also allows view-only), optionally until --expires-at.
|
|
37
|
+
* @param {string[]} positional @param {SupportFlags} flags @param {Deps} [deps]
|
|
38
|
+
*/
|
|
39
|
+
async function supportStaffGrant(positional, flags, deps = {}) {
|
|
40
|
+
const label = 'permissions support-staff grant'
|
|
41
|
+
const suid = suidOf(label, positional)
|
|
42
|
+
const roleId = roleOf(label, flags)
|
|
43
|
+
const body = await permissionsRequest(label, flags, deps, 'POST', `/users/${encodeURIComponent(suid)}/roles`, { roleId, ...(flags['expires-at'] ? { expiresAt: flags['expires-at'] } : {}) })
|
|
44
|
+
return body.data.attributes
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Revoke <suid>'s support role for --mode.
|
|
49
|
+
* @param {string[]} positional @param {SupportFlags} flags @param {Deps} [deps]
|
|
50
|
+
*/
|
|
51
|
+
async function supportStaffRevoke(positional, flags, deps = {}) {
|
|
52
|
+
const label = 'permissions support-staff revoke'
|
|
53
|
+
const suid = suidOf(label, positional)
|
|
54
|
+
const roleId = roleOf(label, flags)
|
|
55
|
+
await permissionsRequest(label, flags, deps, 'DELETE', `/users/${encodeURIComponent(suid)}/roles/${encodeURIComponent(roleId)}`)
|
|
56
|
+
return { userId: suid, roleId, revoked: true }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Every support staff member: who, the mode their role allows at most, and its expiry.
|
|
61
|
+
* @param {string[]} positional @param {SupportFlags} flags @param {Deps} [deps]
|
|
62
|
+
*/
|
|
63
|
+
async function supportStaffList(positional, flags, deps = {}) {
|
|
64
|
+
const rows = []
|
|
65
|
+
for (const [mode, roleId] of Object.entries(ROLE_BY_MODE)) {
|
|
66
|
+
const body = await permissionsRequest('permissions support-staff list', flags, deps, 'GET', `/roles/${encodeURIComponent(roleId)}/assignments`)
|
|
67
|
+
for (const d of body.data || []) rows.push({ userId: d.attributes.userId, mode, roleId, expiresAt: d.attributes.expiresAt || null })
|
|
68
|
+
}
|
|
69
|
+
return rows
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
module.exports = { supportStaffGrant, supportStaffRevoke, supportStaffList, ROLE_BY_MODE }
|