saaslayer 0.0.7 → 0.2.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 +150 -13
- package/bin/saaslayer.js +318 -66
- package/package.json +4 -3
- package/src/api-client.js +48 -28
- package/src/aws-sigv4.js +1 -1
- package/src/commands/access-admins.js +73 -0
- package/src/commands/accounts.js +32 -3
- package/src/commands/activity.js +33 -0
- package/src/commands/aws.js +55 -6
- package/src/commands/catalog.js +30 -29
- package/src/commands/context.js +64 -0
- package/src/commands/deploy.js +79 -10
- package/src/commands/first-admin.js +42 -0
- package/src/commands/foundation.js +456 -0
- package/src/commands/integration-credentials.js +66 -0
- package/src/commands/lifecycle.js +77 -40
- package/src/commands/login.js +200 -26
- package/src/commands/machine-trust.js +96 -0
- package/src/commands/operations.js +140 -0
- package/src/commands/orgs.js +29 -4
- package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
- package/src/commands/release-manifest.js +138 -0
- package/src/commands/service-principals.js +81 -0
- package/src/commands/settings.js +140 -0
- package/src/commands/stacks.js +12 -7
- package/src/commands/users-management.js +401 -0
- package/src/commands/users.js +192 -4
- package/src/config.js +20 -7
- package/src/credentials.js +221 -34
- package/src/deployment-api-auth.js +61 -0
- package/src/deployment-auth.js +38 -0
- package/src/deployments.js +12 -13
- package/src/discovery.js +66 -0
- package/src/env-compare.js +143 -0
- package/src/iam-session.js +4 -30
- package/src/module-catalog.js +66 -0
- package/src/permissions-request.js +43 -0
- package/src/release-manifest.js +334 -0
- package/src/scope.js +114 -0
- package/src/settings.js +272 -0
- package/src/users-api.js +165 -0
- package/src/users-import/import.js +10 -10
- package/templates/saaslayer-foundation-region.yml +37 -1
- package/templates/saaslayer-foundation.yml +63 -10
- package/src/commands/iam-principals.js +0 -53
- package/src/rbac-auth.js +0 -25
- package/vendor/ids/index.d.ts +0 -21
- package/vendor/ids/index.js +0 -237
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
// `saaslayer users admin bootstrap|keys|grants`: opt-in local management of one user-service instance. Standalone, with the
|
|
2
|
+
// owner's target-account IAM against a checked manifest; managed, through the control plane as an owner of the owning org.
|
|
3
|
+
'use strict'
|
|
4
|
+
const fs = require('fs')
|
|
5
|
+
const path = require('path')
|
|
6
|
+
const crypto = require('crypto')
|
|
7
|
+
const { execFileSync } = require('child_process')
|
|
8
|
+
const { apiCall } = require('../api-client')
|
|
9
|
+
const { signRequest } = require('../aws-sigv4')
|
|
10
|
+
const { awsCredentials } = require('../iam-session')
|
|
11
|
+
|
|
12
|
+
// The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
|
|
13
|
+
// vendor/user-management, synced on prepack).
|
|
14
|
+
const MONOREPO_MANAGEMENT = path.join(__dirname, '../../../../services/user-service/src/management')
|
|
15
|
+
|
|
16
|
+
/** The user-service management package: registry, purposes and the request flow its seed also runs. */
|
|
17
|
+
function loadManagement() {
|
|
18
|
+
try {
|
|
19
|
+
return require('../../vendor/user-management')
|
|
20
|
+
} catch (err) {
|
|
21
|
+
if (err && err.code !== 'MODULE_NOT_FOUND') throw err
|
|
22
|
+
return require(MONOREPO_MANAGEMENT)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const SUBCOMMANDS = ['bootstrap', 'keys', 'grants']
|
|
27
|
+
const KEY_PHASES = ['introduce', 'activate', 'retire', 'revoke', 'status']
|
|
28
|
+
const GRANT_PHASES = ['grant', 'revoke', 'status']
|
|
29
|
+
const MANIFEST_FIELDS = ['deploymentId', 'serviceRef', 'accountId', 'region', 'stackName', 'userPoolId', 'managementTableName', 'managementMaterialPath']
|
|
30
|
+
|
|
31
|
+
const USAGE = `usage: saaslayer users admin <bootstrap|keys|grants> --deployment <id> --service <ref> --account-id <id> --region <r>
|
|
32
|
+
[--profile <p> --manifest <file>] (standalone: your target-account IAM; otherwise through the control plane)
|
|
33
|
+
bootstrap --owner-suid <suid> --owner-email <email> [repeat the pair] --purpose <purpose> [repeatable] [--reason <text>]
|
|
34
|
+
keys --caller <id> --purpose <purpose> --phase introduce --output <private-file>
|
|
35
|
+
keys --caller <id> --phase activate|retire|revoke --key-id <id> [--reason <text>] | keys --phase status
|
|
36
|
+
grants --principal <suid> [repeatable] --purpose <purpose> --phase grant|revoke|status [--reason <text>]`
|
|
37
|
+
|
|
38
|
+
/** @param {unknown} value @returns {string[]} */
|
|
39
|
+
const listOf = (value) => (value === undefined || value === true ? [] : Array.isArray(value) ? value.map(String) : [String(value)])
|
|
40
|
+
|
|
41
|
+
/** @param {Record<string, any>} flags @param {string} name */
|
|
42
|
+
function required(flags, name) {
|
|
43
|
+
const value = flags[name]
|
|
44
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error(`--${name} is required\n${USAGE}`)
|
|
45
|
+
return value.trim()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** @param {Record<string, any>} flags @param {string} name */
|
|
49
|
+
const optional = (flags, name) => (typeof flags[name] === 'string' && flags[name].trim() ? flags[name].trim() : undefined)
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The instance every subcommand names: deployment, service ref, account and region.
|
|
53
|
+
* @param {Record<string, any>} flags
|
|
54
|
+
*/
|
|
55
|
+
function instanceOf(flags) {
|
|
56
|
+
const deploymentId = required(flags, 'deployment')
|
|
57
|
+
const serviceRef = required(flags, 'service')
|
|
58
|
+
const accountId = required(flags, 'account-id')
|
|
59
|
+
const region = required(flags, 'region')
|
|
60
|
+
if (!/^[0-9]{12}$/.test(accountId)) throw new Error('--account-id must be a 12-digit AWS account id')
|
|
61
|
+
if (!/^user-service(@[a-z][a-z0-9]{0,11})?$/.test(serviceRef)) throw new Error('--service must be user-service or user-service@<instance>')
|
|
62
|
+
return { deploymentId, serviceRef, accountId, region }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The checked request(s) of a subcommand, before any I/O. A grants run carries one request per --principal.
|
|
67
|
+
* @param {string} sub @param {Record<string, any>} flags
|
|
68
|
+
* @returns {Array<Record<string, any>>}
|
|
69
|
+
*/
|
|
70
|
+
function requestsOf(sub, flags) {
|
|
71
|
+
const reason = optional(flags, 'reason')
|
|
72
|
+
const purposes = listOf(flags.purpose)
|
|
73
|
+
if (sub === 'bootstrap') {
|
|
74
|
+
const suids = listOf(flags['owner-suid'])
|
|
75
|
+
const emails = listOf(flags['owner-email'])
|
|
76
|
+
if (suids.length === 0) throw new Error(`--owner-suid is required\n${USAGE}`)
|
|
77
|
+
if (suids.length !== emails.length) throw new Error('pair every --owner-suid with an --owner-email, in the same order')
|
|
78
|
+
if (purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
|
|
79
|
+
// A reason makes this an explicit, audited owner action: adding a root to an initialized instance, or recovering one.
|
|
80
|
+
return [{ action: 'bootstrap', owners: suids.map((suid, i) => ({ suid, email: emails[i], purposes })), ...(reason ? { reason, recover: true } : {}) }]
|
|
81
|
+
}
|
|
82
|
+
const phase = required(flags, 'phase')
|
|
83
|
+
if (sub === 'keys') {
|
|
84
|
+
if (!KEY_PHASES.includes(phase)) throw new Error(`--phase must be one of ${KEY_PHASES.join(', ')}`)
|
|
85
|
+
if (phase === 'status') return [{ action: 'key', phase }]
|
|
86
|
+
const callerId = required(flags, 'caller')
|
|
87
|
+
if (phase === 'introduce') {
|
|
88
|
+
required(flags, 'output')
|
|
89
|
+
if (purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
|
|
90
|
+
return [{ action: 'key', phase, callerId, purposes }]
|
|
91
|
+
}
|
|
92
|
+
const keyId = required(flags, 'key-id')
|
|
93
|
+
if (phase === 'revoke' && !reason) throw new Error('--reason is required to revoke a key')
|
|
94
|
+
return [{ action: 'key', phase, callerId, keyId, ...(reason ? { reason } : {}) }]
|
|
95
|
+
}
|
|
96
|
+
if (!GRANT_PHASES.includes(phase)) throw new Error(`--phase must be one of ${GRANT_PHASES.join(', ')}`)
|
|
97
|
+
if (phase === 'status') return [{ action: 'grant', phase }]
|
|
98
|
+
const principals = listOf(flags.principal)
|
|
99
|
+
if (principals.length === 0) throw new Error(`--principal is required (repeatable)\n${USAGE}`)
|
|
100
|
+
if (phase === 'grant' && purposes.length === 0) throw new Error(`--purpose is required (repeatable)\n${USAGE}`)
|
|
101
|
+
if (phase === 'revoke' && !reason) throw new Error('--reason is required to revoke a grant')
|
|
102
|
+
return principals.map((principal) => ({ action: 'grant', phase, principal, ...(phase === 'grant' ? { purposes } : {}), ...(reason ? { reason } : {}) }))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Write an issued raw key to the caller's private file (0600, never overwritten). A retry re-outputting the same key is
|
|
107
|
+
* fine; a file holding anything else is refused.
|
|
108
|
+
* @param {string} file @param {string} key
|
|
109
|
+
*/
|
|
110
|
+
function writeKeyFile(file, key) {
|
|
111
|
+
try {
|
|
112
|
+
fs.writeFileSync(file, `${key}\n`, { mode: 0o600, flag: 'wx' })
|
|
113
|
+
} catch (err) {
|
|
114
|
+
if (!err || /** @type {{ code?: string }} */ (err).code !== 'EEXIST') throw err
|
|
115
|
+
if (fs.readFileSync(file, 'utf8').trim() !== key) throw new Error(`--output ${file} already exists and holds something else; choose a new file`)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Claim --output for a key the control plane returns once: a new private file (0600), created exclusively, so an existing
|
|
121
|
+
* file or a symlink is refused before anything is requested.
|
|
122
|
+
* @param {string} file
|
|
123
|
+
* @returns {number} the open file descriptor
|
|
124
|
+
*/
|
|
125
|
+
function claimKeyFile(file) {
|
|
126
|
+
try {
|
|
127
|
+
return fs.openSync(file, 'wx', 0o600)
|
|
128
|
+
} catch (err) {
|
|
129
|
+
const code = /** @type {{ code?: string }} */ (err).code
|
|
130
|
+
if (code === 'EEXIST') throw new Error(`--output ${file} already exists (or is a link); a managed key is returned once, so choose a new file`)
|
|
131
|
+
throw new Error(`--output ${file} cannot be created: ${/** @type {Error} */ (err).message}`)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// ---- standalone: the owner's target-account IAM ------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
/** @param {string} cmd @param {string[]} args */
|
|
138
|
+
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The manifest, checked against the flags and its own derivations before anything is called.
|
|
142
|
+
* @param {string} file @param {ReturnType<typeof instanceOf>} instance @param {ReturnType<typeof loadManagement>} management
|
|
143
|
+
*/
|
|
144
|
+
function checkedManifest(file, instance, management) {
|
|
145
|
+
let manifest
|
|
146
|
+
try {
|
|
147
|
+
manifest = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
148
|
+
} catch (err) {
|
|
149
|
+
throw new Error(`--manifest ${file} is not a readable JSON file: ${/** @type {Error} */ (err).message}`)
|
|
150
|
+
}
|
|
151
|
+
const missing = MANIFEST_FIELDS.filter((f) => typeof manifest[f] !== 'string' || !manifest[f])
|
|
152
|
+
if (missing.length) throw new Error(`the manifest lacks ${missing.join(', ')}`)
|
|
153
|
+
for (const [field, flag] of [['deploymentId', 'deploymentId'], ['serviceRef', 'serviceRef'], ['accountId', 'accountId'], ['region', 'region']]) {
|
|
154
|
+
if (manifest[field] !== instance[/** @type {keyof typeof instance} */ (flag)]) throw new Error(`the manifest names ${field} ${manifest[field]}, not ${instance[/** @type {keyof typeof instance} */ (flag)]}; refusing a write to another target`)
|
|
155
|
+
}
|
|
156
|
+
const materialPath = management.managementMaterialPath(manifest.deploymentId, manifest.serviceRef)
|
|
157
|
+
if (manifest.managementMaterialPath !== materialPath) throw new Error(`the manifest's managementMaterialPath is not this instance's (${materialPath})`)
|
|
158
|
+
return manifest
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The instance's pending key material in the owner-only SSM path: create-only SecureStrings, read back for a retry,
|
|
163
|
+
* removed once the key is no longer pending. Signed with the owner's credentials (no SDK; the raw value never reaches a
|
|
164
|
+
* process argument).
|
|
165
|
+
* @param {{ region: string, credentials: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, basePath: string, fetchImpl: typeof fetch }} deps
|
|
166
|
+
*/
|
|
167
|
+
function ssmMaterial({ region, credentials, basePath, fetchImpl }) {
|
|
168
|
+
const host = `ssm.${region}.amazonaws.com`
|
|
169
|
+
/** @param {string} action @param {Record<string, unknown>} input */
|
|
170
|
+
async function call(action, input) {
|
|
171
|
+
const body = JSON.stringify(input)
|
|
172
|
+
const { headers } = signRequest({
|
|
173
|
+
method: 'POST',
|
|
174
|
+
url: `https://${host}/`,
|
|
175
|
+
body,
|
|
176
|
+
region,
|
|
177
|
+
service: 'ssm',
|
|
178
|
+
credentials: credentials(),
|
|
179
|
+
headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': `AmazonSSM.${action}`, Host: host },
|
|
180
|
+
})
|
|
181
|
+
const res = await fetchImpl(`https://${host}/`, { method: 'POST', headers, body })
|
|
182
|
+
const doc = await res.json().catch(() => ({}))
|
|
183
|
+
if (res.ok) return doc
|
|
184
|
+
const type = String((doc && (doc.__type || doc.code)) || '').split('#').pop()
|
|
185
|
+
throw Object.assign(new Error(`SSM ${action} failed (${res.status}${type ? ` ${type}` : ''})`), { name: type || 'SsmError' })
|
|
186
|
+
}
|
|
187
|
+
const name = (/** @type {string} */ keyId) => `${basePath}/${keyId}`
|
|
188
|
+
return {
|
|
189
|
+
async put(/** @type {string} */ keyId, /** @type {string} */ raw) {
|
|
190
|
+
await call('PutParameter', { Name: name(keyId), Value: raw, Type: 'SecureString', Overwrite: false, Description: 'pending local management key (owner only)' })
|
|
191
|
+
},
|
|
192
|
+
async get(/** @type {string} */ keyId) {
|
|
193
|
+
try {
|
|
194
|
+
const doc = await call('GetParameter', { Name: name(keyId), WithDecryption: true })
|
|
195
|
+
return doc.Parameter ? String(doc.Parameter.Value) : null
|
|
196
|
+
} catch (err) {
|
|
197
|
+
if (/** @type {{ name?: string }} */ (err).name === 'ParameterNotFound') return null
|
|
198
|
+
throw err
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
async remove(/** @type {string} */ keyId) {
|
|
202
|
+
try {
|
|
203
|
+
await call('DeleteParameter', { Name: name(keyId) })
|
|
204
|
+
} catch (err) {
|
|
205
|
+
if (/** @type {{ name?: string }} */ (err).name !== 'ParameterNotFound') throw err
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The own pool through the aws CLI with the owner's credentials: the account holding an email (its custom:suid and sub),
|
|
213
|
+
* and an invitation creating one at a suid (its sub).
|
|
214
|
+
* @param {{ exec: typeof defaultExec, awsArgs: string[], userPoolId: string }} deps
|
|
215
|
+
*/
|
|
216
|
+
function poolAccounts({ exec, awsArgs, userPoolId }) {
|
|
217
|
+
return {
|
|
218
|
+
async get(/** @type {string} */ email) {
|
|
219
|
+
let out
|
|
220
|
+
try {
|
|
221
|
+
out = JSON.parse(exec('aws', ['cognito-idp', 'admin-get-user', '--user-pool-id', userPoolId, '--username', email, '--output', 'json', ...awsArgs]))
|
|
222
|
+
} catch (err) {
|
|
223
|
+
if (String(/** @type {{ stderr?: unknown }} */ (err).stderr || '').includes('UserNotFoundException')) return null
|
|
224
|
+
throw new Error('reading the owner account failed (aws cognito-idp admin-get-user)')
|
|
225
|
+
}
|
|
226
|
+
return { suid: attributeOf(out.UserAttributes, 'custom:suid'), sub: attributeOf(out.UserAttributes, 'sub') }
|
|
227
|
+
},
|
|
228
|
+
async invite(/** @type {{ email: string, suid: string }} */ { email, suid }) {
|
|
229
|
+
const out = JSON.parse(exec('aws', ['cognito-idp', 'admin-create-user', '--user-pool-id', userPoolId, '--username', email, '--desired-delivery-mediums', 'EMAIL',
|
|
230
|
+
'--user-attributes', `Name=email,Value=${email}`, 'Name=email_verified,Value=true', `Name=custom:suid,Value=${suid}`, '--output', 'json', ...awsArgs]))
|
|
231
|
+
return { sub: attributeOf(out.User && out.User.Attributes, 'sub') }
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* A Cognito attribute's value from an aws CLI attribute list, or null.
|
|
238
|
+
* @param {unknown} attributes @param {string} name
|
|
239
|
+
* @returns {string|null}
|
|
240
|
+
*/
|
|
241
|
+
function attributeOf(attributes, name) {
|
|
242
|
+
const found = (Array.isArray(attributes) ? attributes : []).find((/** @type {{ Name?: string }} */ a) => a && a.Name === name)
|
|
243
|
+
return found && found.Value ? String(found.Value) : null
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Check the target (manifest vs flags, the caller's account, the stack's outputs) and build the registry and its ports
|
|
248
|
+
* with the owner's credentials. Nothing is written until every check passed.
|
|
249
|
+
* @param {Record<string, any>} flags @param {ReturnType<typeof instanceOf>} instance @param {Record<string, any>} deps
|
|
250
|
+
*/
|
|
251
|
+
async function standaloneTarget(flags, instance, deps) {
|
|
252
|
+
const management = loadManagement()
|
|
253
|
+
const manifest = checkedManifest(required(flags, 'manifest'), instance, management)
|
|
254
|
+
const exec = deps.exec || defaultExec
|
|
255
|
+
const awsArgs = ['--region', manifest.region, ...(flags.profile ? ['--profile', String(flags.profile)] : [])]
|
|
256
|
+
const identity = JSON.parse(exec('aws', ['sts', 'get-caller-identity', '--output', 'json', ...awsArgs]))
|
|
257
|
+
if (identity.Account !== manifest.accountId) throw new Error(`your credentials are for account ${identity.Account}, not the manifest's ${manifest.accountId}`)
|
|
258
|
+
const outputs = Object.fromEntries((JSON.parse(exec('aws', ['cloudformation', 'describe-stacks', '--stack-name', manifest.stackName, '--query', 'Stacks[0].Outputs', '--output', 'json', ...awsArgs])) || [])
|
|
259
|
+
.map((/** @type {{ OutputKey: string, OutputValue: string }} */ o) => [o.OutputKey, o.OutputValue]))
|
|
260
|
+
if (outputs.UserPoolId !== manifest.userPoolId) throw new Error(`stack ${manifest.stackName} reports UserPoolId ${outputs.UserPoolId || '(none)'}, not the manifest's`)
|
|
261
|
+
if (outputs.ManagementTableName !== manifest.managementTableName) throw new Error(`stack ${manifest.stackName} reports ManagementTableName ${outputs.ManagementTableName || '(none)'}, not the manifest's`)
|
|
262
|
+
const credentials = deps.credentials || (() => awsCredentials({ profile: flags.profile }))
|
|
263
|
+
const doc = deps.doc || standaloneDocumentClient(manifest.region, credentials)
|
|
264
|
+
return {
|
|
265
|
+
management,
|
|
266
|
+
actor: { kind: 'aws-principal', id: identity.Arn },
|
|
267
|
+
registry: management.createManagementRegistry({ doc, tableName: manifest.managementTableName, serviceRef: manifest.serviceRef }),
|
|
268
|
+
accounts: poolAccounts({ exec, awsArgs, userPoolId: manifest.userPoolId }),
|
|
269
|
+
// The stack's own core table: an owner invitation claims its suid's onboarding marker there first, and a grant finds
|
|
270
|
+
// its grantee's account there.
|
|
271
|
+
coreTableName: outputs.CoreTableName || null,
|
|
272
|
+
identity: outputs.CoreTableName ? management.coreIdentity({ doc, tableName: outputs.CoreTableName }) : undefined,
|
|
273
|
+
material: ssmMaterial({ region: manifest.region, credentials, basePath: manifest.managementMaterialPath, fetchImpl: deps.fetch || fetch }),
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* DynamoDB with the owner's credentials (the registry's conditional writes are the authorization: no IAM write, no change).
|
|
279
|
+
* @param {string} region @param {() => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }} credentials
|
|
280
|
+
*/
|
|
281
|
+
function standaloneDocumentClient(region, credentials) {
|
|
282
|
+
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
|
|
283
|
+
const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb')
|
|
284
|
+
return DynamoDBDocumentClient.from(new DynamoDBClient({ region, credentials: async () => credentials() }), { marshallOptions: { removeUndefinedValues: true } })
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---- output -------------------------------------------------------------------------------------------------------
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* The lines a result prints: owners and outcomes, key ids and states with age, grants; never an email, hash or raw key.
|
|
291
|
+
* @param {Record<string, any>} result
|
|
292
|
+
* @returns {string[]}
|
|
293
|
+
*/
|
|
294
|
+
function formatResult(result) {
|
|
295
|
+
if (Array.isArray(result.owners)) return result.owners.map((o) => `${o.suid} ${o.account || ''} ${o.outcome}`.replace(/\s{3,}/g, ' '))
|
|
296
|
+
if (Array.isArray(result.callers)) {
|
|
297
|
+
const lines = []
|
|
298
|
+
for (const c of result.callers) {
|
|
299
|
+
const keys = c.keys || []
|
|
300
|
+
if (c.callerType === 'machine') {
|
|
301
|
+
if (keys.length === 0) lines.push(`${c.callerId} (no keys) ${c.purposes.join(',')}`)
|
|
302
|
+
for (const k of keys) lines.push(`${c.callerId} ${k.keyId} ${k.state} age ${k.ageDays}d ${c.purposes.join(',')}`)
|
|
303
|
+
} else {
|
|
304
|
+
lines.push(`${c.callerId} grant ${c.status} ${c.purposes.join(',')}`)
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return lines.length ? lines : ['no local management callers']
|
|
308
|
+
}
|
|
309
|
+
if (result.principal) return [`${result.principal} ${result.outcome}`]
|
|
310
|
+
if (result.keyId) return [`${result.callerId} ${result.keyId} ${result.state || (result.phase === 'introduce' ? 'next (pending)' : '')}${result.reused ? ' (pending key re-issued)' : ''}`]
|
|
311
|
+
return [JSON.stringify(result)]
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// ---- managed: through the control plane ---------------------------------------------------------------------------
|
|
315
|
+
|
|
316
|
+
const ROUTE = { bootstrap: 'bootstrap', keys: 'keys', grants: 'grants' }
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* One managed request: the deployment must be the named target; the owner route starts the operation; an issued key goes
|
|
320
|
+
* only to --output.
|
|
321
|
+
* @param {string} sub @param {Record<string, any>} request @param {ReturnType<typeof instanceOf>} instance @param {Record<string, any>} flags
|
|
322
|
+
* @param {(line: string) => void} log
|
|
323
|
+
*/
|
|
324
|
+
async function managedRequest(sub, request, instance, flags, log) {
|
|
325
|
+
const { action, ...attributes } = request
|
|
326
|
+
if (attributes.recover) delete attributes.recover
|
|
327
|
+
const file = String(flags.output)
|
|
328
|
+
const fd = action === 'key' && request.phase === 'introduce' ? claimKeyFile(file) : null
|
|
329
|
+
let attrs
|
|
330
|
+
try {
|
|
331
|
+
const doc = await apiCall('POST', `/api/deployments/${encodeURIComponent(instance.deploymentId)}/services/${encodeURIComponent(instance.serviceRef)}/admin/${ROUTE[/** @type {keyof typeof ROUTE} */ (sub)]}`,
|
|
332
|
+
{ data: { type: 'management-requests', attributes } }, flags, { headers: { 'Idempotency-Key': `cli-${crypto.randomUUID()}` } })
|
|
333
|
+
attrs = (doc && doc.data && doc.data.attributes) || {}
|
|
334
|
+
if (fd !== null && attrs.key) fs.writeSync(fd, `${attrs.key}\n`)
|
|
335
|
+
} catch (err) {
|
|
336
|
+
if (fd !== null) {
|
|
337
|
+
fs.closeSync(fd)
|
|
338
|
+
fs.rmSync(file, { force: true })
|
|
339
|
+
}
|
|
340
|
+
throw err
|
|
341
|
+
}
|
|
342
|
+
if (fd !== null) {
|
|
343
|
+
fs.closeSync(fd)
|
|
344
|
+
if (!attrs.key) fs.rmSync(file, { force: true })
|
|
345
|
+
}
|
|
346
|
+
if (attrs.key) log(`key ${attrs.keyId} for ${request.callerId} written to ${file} (pending until activated)`)
|
|
347
|
+
log(`operation ${attrs.operationId} ${attrs.status || 'started'} — follow with \`saaslayer operations watch ${attrs.operationId} --deployment ${instance.deploymentId}\``)
|
|
348
|
+
if (flags.wait) {
|
|
349
|
+
const { followOperation } = require('./operations')
|
|
350
|
+
const final = await followOperation({ deploymentId: instance.deploymentId, operationId: attrs.operationId, flags })
|
|
351
|
+
const component = (final.components || []).find((c) => c.name === 'management')
|
|
352
|
+
const result = component && component.detail && component.detail.request && component.detail.request.result
|
|
353
|
+
if (result) for (const line of formatResult(result)) log(line)
|
|
354
|
+
}
|
|
355
|
+
return attrs
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Run `saaslayer users admin <sub>`. deps (tests): exec, fetch, doc, credentials, log.
|
|
360
|
+
* @param {string} sub @param {Record<string, any>} flags @param {Record<string, any>} [deps]
|
|
361
|
+
*/
|
|
362
|
+
async function usersManagement(sub, flags, deps = {}) {
|
|
363
|
+
if (!SUBCOMMANDS.includes(sub)) throw new Error(USAGE)
|
|
364
|
+
const log = deps.log || ((/** @type {string} */ line) => console.log(line))
|
|
365
|
+
const instance = instanceOf(flags)
|
|
366
|
+
const requests = requestsOf(sub, flags)
|
|
367
|
+
if (!flags.manifest) {
|
|
368
|
+
const deployment = await apiCall('GET', `/api/deployments/${encodeURIComponent(instance.deploymentId)}`, undefined, flags)
|
|
369
|
+
const d = (deployment && deployment.data && deployment.data.attributes) || {}
|
|
370
|
+
if (d.accountId !== instance.accountId) throw new Error(`deployment ${instance.deploymentId} is in account ${d.accountId}, not ${instance.accountId}`)
|
|
371
|
+
if (d.region !== instance.region) throw new Error(`deployment ${instance.deploymentId} is in region ${d.region}, not ${instance.region}`)
|
|
372
|
+
const results = []
|
|
373
|
+
for (const request of requests) results.push(await managedRequest(sub, request, instance, flags, log))
|
|
374
|
+
return results
|
|
375
|
+
}
|
|
376
|
+
const target = await standaloneTarget(flags, instance, deps)
|
|
377
|
+
if (requests.some((r) => r.action === 'bootstrap' || (r.action === 'grant' && r.phase === 'grant')) && !target.coreTableName) {
|
|
378
|
+
throw new Error('the stack reports no CoreTableName output: deploy the release that adds it before bootstrapping or granting')
|
|
379
|
+
}
|
|
380
|
+
const results = []
|
|
381
|
+
for (const request of requests) {
|
|
382
|
+
const { management, registry, accounts, identity, material, actor } = target
|
|
383
|
+
let result
|
|
384
|
+
try {
|
|
385
|
+
result = await management.applyManagementRequest({ registry, accounts, identity, request, actor, material })
|
|
386
|
+
} catch (err) {
|
|
387
|
+
const e = /** @type {Error & { code?: string }} */ (err)
|
|
388
|
+
throw new Error(e.code ? `${e.code}: ${e.message}` : e.message)
|
|
389
|
+
}
|
|
390
|
+
if (result.key) {
|
|
391
|
+
writeKeyFile(String(flags.output), String(result.key))
|
|
392
|
+
log(`key ${result.keyId} for ${result.callerId} written to ${flags.output} (pending until activated)`)
|
|
393
|
+
delete result.key
|
|
394
|
+
}
|
|
395
|
+
for (const line of formatResult(result)) log(line)
|
|
396
|
+
results.push(result)
|
|
397
|
+
}
|
|
398
|
+
return results
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
module.exports = { usersManagement, requestsOf, formatResult, ssmMaterial, loadManagement, USAGE, SUBCOMMANDS }
|
package/src/commands/users.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// `saaslayer users
|
|
2
|
-
//
|
|
1
|
+
// `saaslayer users …`: move people from another identity system into a deployment (export a reviewable manifest, import
|
|
2
|
+
// it), and administer its users through user-service /api/users as a deployment login, an IAM principal or an API key.
|
|
3
3
|
'use strict'
|
|
4
4
|
const fs = require('fs')
|
|
5
5
|
const path = require('path')
|
|
@@ -8,8 +8,12 @@ const { getProvider } = require('../users-import/providers')
|
|
|
8
8
|
const { buildManifest, validateManifest } = require('../users-import/manifest')
|
|
9
9
|
const { planImport, applyImport, formatPlan } = require('../users-import/import')
|
|
10
10
|
const { mintSuid } = require('../users-import/ids')
|
|
11
|
-
const { authHeaders } = require('../
|
|
11
|
+
const { authHeaders } = require('../deployment-api-auth')
|
|
12
12
|
const { exchangeIamToken } = require('../iam-session')
|
|
13
|
+
const creds = require('../credentials')
|
|
14
|
+
const { discoverDeployment, discoverFromFlags } = require('../discovery')
|
|
15
|
+
const { usersApi, readPasswordFromStdin, defaultCreateKey } = require('../users-api')
|
|
16
|
+
const { loadOperations, intervalMs } = require('./operations')
|
|
13
17
|
|
|
14
18
|
/** @param {string} cmd @param {string[]} args */
|
|
15
19
|
const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
|
|
@@ -78,4 +82,188 @@ async function usersImport(flags, deps = {}) {
|
|
|
78
82
|
return { plan, report }
|
|
79
83
|
}
|
|
80
84
|
|
|
81
|
-
|
|
85
|
+
/** The per-user administration subcommands (`saaslayer users <sub>`), in help order. */
|
|
86
|
+
const ADMIN_COMMANDS = ['create', 'get', 'list', 'update', 'disable', 'enable', 'delete', 'reset-password', 'set-password', 'adopt', 'reset-mfa']
|
|
87
|
+
|
|
88
|
+
const USAGE = `usage: saaslayer users <${['export', 'import', ...ADMIN_COMMANDS].join('|')}> … (see saaslayer --help)`
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @typedef {{ stdin?: NodeJS.ReadableStream, log?: (line: string) => void, fetch?: typeof fetch,
|
|
92
|
+
* exchange?: typeof exchangeIamToken, discover?: typeof discoverDeployment, sleep?: (ms: number) => Promise<void> }} AdminDeps
|
|
93
|
+
* @typedef {ReturnType<typeof usersApi>} UsersApi
|
|
94
|
+
*/
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The users API a command acts on and how it authenticates. Auth: --iam (IAM principal token), --token (API key), else
|
|
98
|
+
* the selected deployment login (--deployment/--as/--user-service-instance, or the current one) — see deployment-api-auth.js.
|
|
99
|
+
* API bases: --api-base (+ --permissions-api-base for --iam), else the deployment login's own, else (with --iam/--token)
|
|
100
|
+
* discovered from the deployment's public outputs (--deployment <dep_id|env> or --discovery-url).
|
|
101
|
+
* @param {string} command @param {Record<string, any>} flags @param {AdminDeps} deps
|
|
102
|
+
* @returns {Promise<UsersApi>}
|
|
103
|
+
*/
|
|
104
|
+
async function usersTarget(command, flags, deps) {
|
|
105
|
+
const exchange = deps.exchange || exchangeIamToken
|
|
106
|
+
let apiBase = flags['api-base'] || process.env.SAASLAYER_USERS_API_BASE
|
|
107
|
+
let permissionsApiBase = flags['permissions-api-base'] || process.env.SAASLAYER_API_BASE
|
|
108
|
+
const machine = Boolean(flags.iam || flags.token)
|
|
109
|
+
if (!apiBase && machine) {
|
|
110
|
+
if (!flags.deployment && !flags['discovery-url']) throw new Error(`users ${command}: --api-base, --deployment or --discovery-url is required with --iam/--token`)
|
|
111
|
+
const { doc } = await discoverFromFlags(flags, { discover: deps.discover })
|
|
112
|
+
apiBase = doc.usersApiBase
|
|
113
|
+
permissionsApiBase = permissionsApiBase || doc.permissionsApiBase
|
|
114
|
+
}
|
|
115
|
+
if (!apiBase) apiBase = creds.selectDeploymentProfile(flags).usersApiBase
|
|
116
|
+
if (flags.iam && !permissionsApiBase) throw new Error(`users ${command}: --permissions-api-base (the permissions API for the IAM exchange, or $SAASLAYER_API_BASE) is required with --iam`)
|
|
117
|
+
/** @type {Promise<Record<string, string>>|null} */
|
|
118
|
+
let headers = null
|
|
119
|
+
const resolveHeaders = () => {
|
|
120
|
+
headers = headers || authHeaders(apiBase, flags, { exchange: (o) => exchange({ ...o, apiBase: permissionsApiBase }) })
|
|
121
|
+
return headers
|
|
122
|
+
}
|
|
123
|
+
return usersApi({ apiBase, headers: resolveHeaders }, { fetch: deps.fetch })
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The password from stdin when --password-stdin is set; a --password flag is refused (shell history, process list).
|
|
128
|
+
* @param {string} command @param {Record<string, any>} flags @param {NodeJS.ReadableStream} stdin
|
|
129
|
+
* @returns {Promise<string|undefined>}
|
|
130
|
+
*/
|
|
131
|
+
async function passwordFlag(command, flags, stdin) {
|
|
132
|
+
if (flags.password !== undefined) throw new Error(`users ${command}: pass the password on stdin with --password-stdin (never as a flag)`)
|
|
133
|
+
return flags['password-stdin'] ? readPasswordFromStdin(stdin) : undefined
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The target user: the positional <suid>, --suid, or --email (looked up: users:read).
|
|
138
|
+
* @param {string} command @param {string[]} args @param {Record<string, any>} flags @param {UsersApi} api
|
|
139
|
+
* @returns {Promise<string>}
|
|
140
|
+
*/
|
|
141
|
+
async function targetSuid(command, args, flags, api) {
|
|
142
|
+
const suid = args[0] || flags.suid
|
|
143
|
+
if (suid) return String(suid)
|
|
144
|
+
if (flags.email) return api.findSuid(String(flags.email))
|
|
145
|
+
throw new Error(`users ${command}: <suid>, --suid or --email is required`)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** --attr name=value (repeatable) plus --name, as profile attributes. @param {Record<string, any>} flags */
|
|
149
|
+
function profileAttributes(flags) {
|
|
150
|
+
/** @type {Record<string, string>} */
|
|
151
|
+
const attrs = flags.name ? { name: String(flags.name) } : {}
|
|
152
|
+
for (const pair of [].concat(flags.attr || [])) {
|
|
153
|
+
const at = String(pair).indexOf('=')
|
|
154
|
+
if (at < 1) throw new Error(`users update: --attr name=value expected, got ${pair}`)
|
|
155
|
+
attrs[String(pair).slice(0, at)] = String(pair).slice(at + 1)
|
|
156
|
+
}
|
|
157
|
+
if (!Object.keys(attrs).length) throw new Error('users update: --name or --attr name=value is required')
|
|
158
|
+
return attrs
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Create a user (a durable operation). --password-stdin gives a permanent password (password initialization: never
|
|
163
|
+
* prod); --delivery invitation mails a temporary one. Re-running the same command replays the same operation (the
|
|
164
|
+
* default Idempotency-Key is derived from the email). A running operation is waited for; a failed component is an
|
|
165
|
+
* error that says to run the same command again, which resumes it.
|
|
166
|
+
* @param {UsersApi} api @param {string[]} args @param {Record<string, any>} flags @param {Required<Pick<AdminDeps, 'stdin'|'log'>> & AdminDeps} deps
|
|
167
|
+
*/
|
|
168
|
+
async function create(api, args, flags, deps) {
|
|
169
|
+
const password = await passwordFlag('create', flags, deps.stdin)
|
|
170
|
+
const attributes = { email: flags.email, password, name: flags.name, soid: flags.soid, suid: flags.suid, delivery: flags.delivery }
|
|
171
|
+
const key = flags['idempotency-key'] || defaultCreateKey(flags.email)
|
|
172
|
+
let result = await api.create(attributes, key)
|
|
173
|
+
const ops = loadOperations()
|
|
174
|
+
if (result.status === 202 && !ops.isTerminal(result.operation.status)) {
|
|
175
|
+
const id = result.operation.id
|
|
176
|
+
const final = await ops.watchOperation({
|
|
177
|
+
id,
|
|
178
|
+
fetchOperation: async () => {
|
|
179
|
+
try {
|
|
180
|
+
return await api.getOperation(id)
|
|
181
|
+
} catch (err) {
|
|
182
|
+
const status = err && /** @type {{ status?: number }} */ (err).status
|
|
183
|
+
if (status && status >= 400 && status < 500 && status !== 408 && status !== 429) Object.assign(err, { fatal: true })
|
|
184
|
+
throw err
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
intervalMs: intervalMs(flags),
|
|
188
|
+
sleep: deps.sleep,
|
|
189
|
+
onUpdate: (op) => { if (!ops.isTerminal(op.status)) deps.log(` … operation ${op.id}: ${op.status}`) },
|
|
190
|
+
resumeCommand: 'run the same command again',
|
|
191
|
+
})
|
|
192
|
+
result = final.status === 'succeeded' ? await api.create(attributes, key) : { ...result, operation: final }
|
|
193
|
+
}
|
|
194
|
+
if (result.status === 202) {
|
|
195
|
+
const op = result.operation
|
|
196
|
+
throw new Error([`users create: operation ${op.id} is ${op.status}; run the same command again to resume it`, ...ops.formatOperation(op).slice(1)].join('\n'))
|
|
197
|
+
}
|
|
198
|
+
return { result, output: { suid: result.user && result.user.id, ...(result.user ? result.user.attributes : {}), operation: result.operation.id } }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Adopt an account made outside SaaSLayer's routes (users:adopt) and, with --password-stdin, give it a permanent
|
|
203
|
+
* password (users:set-password). Both need EnablePasswordInitialization.
|
|
204
|
+
* @param {UsersApi} api @param {string[]} args @param {Record<string, any>} flags @param {Required<Pick<AdminDeps, 'stdin'|'log'>> & AdminDeps} deps
|
|
205
|
+
*/
|
|
206
|
+
async function adopt(api, args, flags, deps) {
|
|
207
|
+
const password = await passwordFlag('adopt', flags, deps.stdin)
|
|
208
|
+
const suid = await targetSuid('adopt', args, flags, api)
|
|
209
|
+
const adopted = await api.adopt(suid)
|
|
210
|
+
if (password) await api.setPassword(suid, password)
|
|
211
|
+
return { suid, adopted: Boolean(adopted.adopted), passwordSet: Boolean(password) }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The per-user subcommands: (api, args, flags, deps) → what is printed.
|
|
216
|
+
* @type {Record<string, (api: UsersApi, args: string[], flags: Record<string, any>, deps: Required<Pick<AdminDeps, 'stdin'|'log'>> & AdminDeps) => Promise<any>>}
|
|
217
|
+
*/
|
|
218
|
+
const HANDLERS = {
|
|
219
|
+
create,
|
|
220
|
+
get: async (api, args, flags) => api.get(await targetSuid('get', args, flags, api), { org: flags.org }),
|
|
221
|
+
list: async (api, args, flags) => {
|
|
222
|
+
if (!flags.email && !flags['default-org']) throw new Error('users list: --email or --default-org is required')
|
|
223
|
+
return api.list({ email: flags.email, defaultOrg: flags['default-org'] }, { limit: flags.limit, cursor: flags.cursor })
|
|
224
|
+
},
|
|
225
|
+
update: async (api, args, flags) => {
|
|
226
|
+
const attributes = profileAttributes(flags)
|
|
227
|
+
return api.update(await targetSuid('update', args, flags, api), attributes)
|
|
228
|
+
},
|
|
229
|
+
disable: async (api, args, flags) => api.disable(await targetSuid('disable', args, flags, api)),
|
|
230
|
+
enable: async (api, args, flags) => api.enable(await targetSuid('enable', args, flags, api)),
|
|
231
|
+
delete: async (api, args, flags) => {
|
|
232
|
+
const suid = args[0] || flags.suid
|
|
233
|
+
if (!suid) throw new Error('users delete: <suid> or --suid is required (--email only helps find a user that was never projected)')
|
|
234
|
+
if (!flags.yes) throw new Error(`users delete: deletes ${suid} everywhere (sign-in, passwordless data, profile) and cannot be undone — pass --yes`)
|
|
235
|
+
return api.remove(String(suid), { email: flags.email })
|
|
236
|
+
},
|
|
237
|
+
'reset-password': async (api, args, flags) => api.resetPassword(await targetSuid('reset-password', args, flags, api)),
|
|
238
|
+
'set-password': async (api, args, flags, deps) => {
|
|
239
|
+
const password = await passwordFlag('set-password', flags, deps.stdin)
|
|
240
|
+
if (!password) throw new Error('users set-password: --password-stdin is required (pipe the password)')
|
|
241
|
+
return api.setPassword(await targetSuid('set-password', args, flags, api), password, { permanent: !flags.temporary })
|
|
242
|
+
},
|
|
243
|
+
adopt,
|
|
244
|
+
'reset-mfa': async (api, args, flags) => {
|
|
245
|
+
const reason = typeof flags.reason === 'string' ? flags.reason.trim() : ''
|
|
246
|
+
if (!reason) throw new Error('users reset-mfa: --reason is required (recorded in the audit line)')
|
|
247
|
+
return api.resetMfa(await targetSuid('reset-mfa', args, flags, api), reason)
|
|
248
|
+
},
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* `saaslayer users <sub>` for one deployment's users through user-service /api/users: prints the result as JSON
|
|
253
|
+
* (secret-named fields redacted) and returns it.
|
|
254
|
+
* @param {string} sub @param {string[]} args positional arguments after the subcommand
|
|
255
|
+
* @param {Record<string, any>} flags @param {AdminDeps} [deps]
|
|
256
|
+
*/
|
|
257
|
+
async function usersAdmin(sub, args, flags, deps = {}) {
|
|
258
|
+
const handler = HANDLERS[sub]
|
|
259
|
+
if (!handler) throw new Error(USAGE)
|
|
260
|
+
const full = { ...deps, stdin: deps.stdin || process.stdin, log: deps.log || console.log }
|
|
261
|
+
if (sub === 'create' && !flags.email) throw new Error('users create: --email is required')
|
|
262
|
+
const api = await usersTarget(sub, flags, full)
|
|
263
|
+
const out = await handler(api, args, flags, full)
|
|
264
|
+
const { result, output } = sub === 'create' ? out : { result: out, output: out }
|
|
265
|
+
full.log(JSON.stringify(loadOperations().redact(output), null, 2))
|
|
266
|
+
return result
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
module.exports = { usersExport, usersImport, usersAdmin, ADMIN_COMMANDS, USAGE }
|
package/src/config.js
CHANGED
|
@@ -2,6 +2,19 @@
|
|
|
2
2
|
// control-plane GET /config endpoint; falls back to flags / env for local + pre-endpoint use.
|
|
3
3
|
'use strict'
|
|
4
4
|
|
|
5
|
+
const DEFAULT_CONTROL_PLANE_URL = 'https://api.saaslayer.com'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The control-plane API base: --config-url, then $SAASLAYER_CONFIG_URL, else the hosted control plane.
|
|
9
|
+
* @param {Record<string, any>} [flags]
|
|
10
|
+
* @returns {{ value: string, source: 'flag' | 'env' | 'default' }}
|
|
11
|
+
*/
|
|
12
|
+
function controlPlaneUrl(flags = {}) {
|
|
13
|
+
if (flags['config-url']) return { value: flags['config-url'], source: 'flag' }
|
|
14
|
+
if (process.env.SAASLAYER_CONFIG_URL) return { value: process.env.SAASLAYER_CONFIG_URL, source: 'env' }
|
|
15
|
+
return { value: DEFAULT_CONTROL_PLANE_URL, source: 'default' }
|
|
16
|
+
}
|
|
17
|
+
|
|
5
18
|
// Decode a JWT payload (middle segment) without verifying — used only to read our own id token's
|
|
6
19
|
// claims (sub, email) after Cognito issued it. Never trust this for authorization.
|
|
7
20
|
function decodeJwt(token) {
|
|
@@ -11,10 +24,13 @@ function decodeJwt(token) {
|
|
|
11
24
|
return JSON.parse(json)
|
|
12
25
|
}
|
|
13
26
|
|
|
27
|
+
// Pool coordinates: an explicit --config-url/$SAASLAYER_CONFIG_URL wins, then explicit pool flags/env, then the
|
|
28
|
+
// default control plane's /api/config.
|
|
14
29
|
async function resolvePoolConfig(flags = {}) {
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
30
|
+
const cp = controlPlaneUrl(flags)
|
|
31
|
+
const explicitPool = (flags['user-pool-id'] || process.env.SAASLAYER_USER_POOL_ID) && (flags['client-id'] || process.env.SAASLAYER_USER_POOL_CLIENT_ID)
|
|
32
|
+
if (cp.source !== 'default' || !explicitPool) {
|
|
33
|
+
const url = `${String(cp.value).replace(/\/$/, '')}/api/config`
|
|
18
34
|
const res = await fetch(url)
|
|
19
35
|
if (!res.ok) throw new Error(`GET ${url} failed (${res.status})`)
|
|
20
36
|
const cfg = await res.json()
|
|
@@ -27,10 +43,7 @@ async function resolvePoolConfig(flags = {}) {
|
|
|
27
43
|
const region = flags.region || process.env.SAASLAYER_USER_POOL_REGION || process.env.AWS_REGION || 'us-east-1'
|
|
28
44
|
const userPoolId = flags['user-pool-id'] || process.env.SAASLAYER_USER_POOL_ID
|
|
29
45
|
const clientId = flags['client-id'] || process.env.SAASLAYER_USER_POOL_CLIENT_ID
|
|
30
|
-
if (!userPoolId || !clientId) {
|
|
31
|
-
throw new Error('user pool not configured: pass --config-url (control-plane), or set SAASLAYER_USER_POOL_ID + SAASLAYER_USER_POOL_CLIENT_ID (or --user-pool-id/--client-id)')
|
|
32
|
-
}
|
|
33
46
|
return { region, userPoolId, clientId }
|
|
34
47
|
}
|
|
35
48
|
|
|
36
|
-
module.exports = { resolvePoolConfig, decodeJwt }
|
|
49
|
+
module.exports = { resolvePoolConfig, decodeJwt, controlPlaneUrl, DEFAULT_CONTROL_PLANE_URL }
|