saaslayer 0.1.0 → 0.3.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.
@@ -3,7 +3,7 @@
3
3
  'use strict'
4
4
  const fs = require('fs')
5
5
  const { execFileSync } = require('child_process')
6
- const { FOUNDATION_TEMPLATE, FOUNDATION_REGION_TEMPLATE, foundationRegionStackName } = require('./aws')
6
+ const { FOUNDATION_TEMPLATE, FOUNDATION_REGION_TEMPLATE, foundationRegionStackName, emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords } = require('./aws')
7
7
  const { stripComments, writeDeployableTemplate } = require('../foundation-template')
8
8
  const { confirm: promptConfirm } = require('../prompt')
9
9
  const { apiCall } = require('../api-client')
@@ -16,7 +16,7 @@ const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', s
16
16
  * @typedef {{ exec?: typeof defaultExec, log?: (...a: unknown[]) => void, confirm?: (q: string) => Promise<boolean>,
17
17
  * sleep?: (ms: number) => Promise<void>, pollMs?: number, maxPolls?: number, refresh?: Refresh }} Deps
18
18
  * @typedef {{ kind: 'account'|'region', stackName: string, template: string, outputKey: string, capabilities: string[] }} Target
19
- * @typedef {{ status: string, version: string|null, paramKeys: string[], lastUpdated: string|null }} InstalledStack
19
+ * @typedef {{ status: string, version: string|null, paramKeys: string[], params: Record<string, string>, outputs: Array<{ OutputKey: string, OutputValue: string }>, lastUpdated: string|null }} InstalledStack
20
20
  * @typedef {{ action: string, logicalId: string, type: string, replacement: string, scope: string[] }} Change
21
21
  */
22
22
 
@@ -159,6 +159,8 @@ function readStack(aws, target) {
159
159
  status: s.StackStatus,
160
160
  version: output ? output.OutputValue : null,
161
161
  paramKeys: (s.Parameters || []).map((p) => p.ParameterKey),
162
+ params: Object.fromEntries((s.Parameters || []).map((p) => [p.ParameterKey, p.ParameterValue])),
163
+ outputs: s.Outputs || [],
162
164
  lastUpdated: s.LastUpdatedTime || s.CreationTime || null,
163
165
  }
164
166
  }
@@ -184,6 +186,27 @@ function versionState(installed, bundledVersion) {
184
186
  * @param {object} flags
185
187
  * @param {Deps} [deps]
186
188
  */
189
+ /**
190
+ * The region stack's email sender domain and its SES verification, when one is set.
191
+ * @param {ReturnType<typeof awsRunner>} aws @param {InstalledStack} installed
192
+ * @returns {{ emailSender?: { domain: string, verified: boolean, dkimStatus: string|null, records: string[] } }}
193
+ */
194
+ function emailSenderStatus(aws, installed) {
195
+ const domain = installed.params.EmailSenderDomain
196
+ if (!domain) return {}
197
+ const sender = emailSenderOutputs(installed.outputs)
198
+ let identity = {}
199
+ try { identity = aws(['sesv2', 'get-email-identity', '--email-identity', domain]) } catch { identity = {} }
200
+ return {
201
+ emailSender: {
202
+ domain,
203
+ verified: identity.VerifiedForSendingStatus === true,
204
+ dkimStatus: (identity.DkimAttributes && identity.DkimAttributes.Status) || null,
205
+ records: sender ? sender.records : [],
206
+ },
207
+ }
208
+ }
209
+
187
210
  async function foundationStatus(flags, { exec = defaultExec, log = console.log } = {}) {
188
211
  const { region, targets } = resolveTargets(flags)
189
212
  const aws = awsRunner(exec, flags, region)
@@ -196,6 +219,7 @@ async function foundationStatus(flags, { exec = defaultExec, log = console.log }
196
219
  installedVersion: installed ? installed.version || 'unknown' : null,
197
220
  bundledVersion,
198
221
  state: versionState(installed, bundledVersion),
222
+ ...(t.kind === 'region' && installed ? emailSenderStatus(aws, installed) : {}),
199
223
  }
200
224
  })
201
225
  for (const r of rows) {
@@ -204,6 +228,11 @@ async function foundationStatus(flags, { exec = defaultExec, log = console.log }
204
228
  log(` installed ${r.installedVersion || '-'}`)
205
229
  log(` bundled ${r.bundledVersion}`)
206
230
  log(` ${r.state}`)
231
+ if (r.emailSender) {
232
+ const e = r.emailSender
233
+ log(` email sender ${e.domain}: ${e.verified ? 'verified' : `not verified yet (DKIM ${e.dkimStatus || 'unknown'})`}`)
234
+ if (!e.verified) for (const record of e.records) log(` ${record}`)
235
+ }
207
236
  }
208
237
  if (rows.some((r) => r.state === 'upgrade available')) log('\nRun `saaslayer foundation upgrade` to review and apply the upgrade.')
209
238
  return rows
@@ -270,6 +299,17 @@ function formatChanges(changes) {
270
299
  return changes.map((c) => ` ${c.action.padEnd(wa)} ${c.logicalId.padEnd(wl)} ${c.type.padEnd(wt)} replacement=${c.replacement || '-'} scope=${c.scope.join(',') || '-'}`)
271
300
  }
272
301
 
302
+ /**
303
+ * After setting a sender domain: the DKIM records the stack now outputs, for the domain's DNS.
304
+ * @param {ReturnType<typeof awsRunner>} aws @param {Target} target @param {string|undefined} domain @param {Function} log
305
+ */
306
+ function logSenderRecords(aws, target, domain, log) {
307
+ if (!domain) return
308
+ const after = readStack(aws, target)
309
+ const sender = after && emailSenderOutputs(after.outputs)
310
+ if (sender) logEmailSenderRecords(log, domain, sender)
311
+ }
312
+
273
313
  /**
274
314
  * Upgrades one foundation stack. Returns { stackName, result, ... } where result is upgraded | up to date | dry-run |
275
315
  * aborted | not installed. Throws on any refusal or failure.
@@ -294,11 +334,19 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
294
334
  throw new Error(`${label} runs ${installed.version}, newer than this CLI's bundled ${info.version}; update the saaslayer CLI instead of downgrading`)
295
335
  }
296
336
  const plan = upgradeParameters(info.parameters, installed.paramKeys)
337
+ // --email-sender-domain sets the region stack's sender domain; every other parameter keeps its value.
338
+ const senderDomain = target.kind === 'region' ? emailSenderDomainFlag(flags) : undefined
339
+ if (senderDomain !== undefined) {
340
+ plan.parameters = plan.parameters.filter((p) => p.ParameterKey !== 'EmailSenderDomain')
341
+ plan.added = plan.added.filter((p) => p.name !== 'EmailSenderDomain')
342
+ plan.parameters.push({ ParameterKey: 'EmailSenderDomain', ParameterValue: senderDomain })
343
+ }
297
344
  const changeSetName = `saaslayer-upgrade-${Date.now()}`
298
345
  const del = () => aws(['cloudformation', 'delete-change-set', '--stack-name', target.stackName, '--change-set-name', changeSetName])
299
346
 
300
347
  log(`\n${label}: ${from} -> ${info.version}`)
301
- log(` parameters kept (previous values): ${plan.parameters.map((p) => p.ParameterKey).join(', ') || '-'}`)
348
+ log(` parameters kept (previous values): ${plan.parameters.filter((p) => p.UsePreviousValue).map((p) => p.ParameterKey).join(', ') || '-'}`)
349
+ if (senderDomain !== undefined) log(` email sender domain: ${senderDomain || '(removed)'}`)
302
350
  if (plan.added.length) log(` new parameters (template default): ${plan.added.map((p) => `${p.name}='${p.default}'`).join(', ')}`)
303
351
  if (plan.removed.length) log(` parameters no longer in the template: ${plan.removed.join(', ')}`)
304
352
 
@@ -314,6 +362,7 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
314
362
  del()
315
363
  if (NO_CHANGES.test(cs.reason)) {
316
364
  log(` no changes — already up to date (${from})`)
365
+ logSenderRecords(aws, target, senderDomain, log)
317
366
  return { stackName: target.stackName, result: 'up to date', installedVersion: installed.version }
318
367
  }
319
368
  throw new Error(`${label}: change set failed: ${cs.reason}`)
@@ -350,6 +399,7 @@ async function upgradeStack(target, flags, { aws, region, required, log, confirm
350
399
  }
351
400
  if (done.version !== info.version) throw new Error(`${label} updated but reports version ${done.version}, expected ${info.version}`)
352
401
  log(` ✅ ${label} upgraded ${from} -> ${done.version}`)
402
+ logSenderRecords(aws, target, senderDomain, log)
353
403
  return { stackName: target.stackName, result: 'upgraded', from, installedVersion: done.version }
354
404
  }
355
405
 
@@ -387,6 +437,7 @@ async function reportToControlPlane(flags, { aws, region, log, refresh }) {
387
437
  * @param {Deps} [deps]
388
438
  */
389
439
  async function foundationUpgrade(flags, { exec = defaultExec, log = console.log, confirm = promptConfirm, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), pollMs = 5000, maxPolls = 720, refresh = refreshFoundationRecord } = {}) {
440
+ emailSenderDomainFlag(flags) // refuse a malformed --email-sender-domain before touching AWS
390
441
  const { region, targets } = resolveTargets(flags)
391
442
  const aws = awsRunner(exec, flags, region)
392
443
  const results = []
@@ -0,0 +1,66 @@
1
+ // `saaslayer credentials status|revoke --deployment <id> --service <ref>`: an org owner reads a user-service instance's
2
+ // integration credentials (key ids, state, age; never a value) or revokes one key (reason required) through the console.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { apiCall } = require('../api-client')
6
+
7
+ const KINDS = ['email-authoring', 'config']
8
+
9
+ /** @param {object} flags @param {string} name */
10
+ const required = (flags, name) => {
11
+ const value = flags[name]
12
+ if (typeof value !== 'string' || !value.trim()) throw new Error(`--${name} is required`)
13
+ return value.trim()
14
+ }
15
+
16
+ /** @param {object} flags */
17
+ function basePath(flags) {
18
+ return `/api/deployments/${encodeURIComponent(required(flags, 'deployment'))}/services/${encodeURIComponent(required(flags, 'service'))}/credentials`
19
+ }
20
+
21
+ /**
22
+ * One line per key and the pending operation, from a status document.
23
+ * @param {Record<string, any>} attrs
24
+ * @returns {string[]}
25
+ */
26
+ function formatStatus(attrs) {
27
+ const lines = []
28
+ for (const [kind, keys] of Object.entries(attrs.kinds || {})) {
29
+ for (const k of keys) lines.push(`${kind} ${k.keyId} ${k.state} age ${k.ageDays}d ${k.accepted ? 'accepted' : 'pending acceptance'}`)
30
+ }
31
+ const op = attrs.operation
32
+ if (op && op.operationId) lines.push(`operation ${op.operationId} ${op.phase} ${op.status}${op.detail ? ` — ${op.detail}` : ''}`)
33
+ return lines.length ? lines : ['no integration credentials']
34
+ }
35
+
36
+ /**
37
+ * Print the instance's integration credentials (or the document with --json) and return its attributes.
38
+ * @param {object} flags
39
+ */
40
+ async function credentialsStatus(flags) {
41
+ const doc = await apiCall('GET', basePath(flags), undefined, flags)
42
+ const attrs = (doc && doc.data && doc.data.attributes) || {}
43
+ console.log(flags.json ? JSON.stringify(attrs, null, 2) : formatStatus(attrs).join('\n'))
44
+ return attrs
45
+ }
46
+
47
+ /**
48
+ * Revoke one key now (no delay). The answer is the pending operation: the old key stops working once every verifier
49
+ * has the replacement; the console sends the replacement only then.
50
+ * @param {object} flags
51
+ */
52
+ async function credentialsRevoke(flags) {
53
+ const kind = required(flags, 'kind')
54
+ if (!KINDS.includes(kind)) throw new Error(`--kind must be one of ${KINDS.join(', ')}`)
55
+ const keyId = required(flags, 'key-id')
56
+ const reason = required(flags, 'reason')
57
+ const path = `${basePath(flags)}/revoke`
58
+ const doc = await apiCall('POST', path, { data: { type: 'credential-revocations', attributes: { kind, keyId, reason } } }, flags, { headers: { 'Idempotency-Key': `cli-${crypto.randomUUID()}` } })
59
+ const attrs = (doc && doc.data && doc.data.attributes) || {}
60
+ console.log(flags.json
61
+ ? JSON.stringify(attrs, null, 2)
62
+ : `revoke of ${keyId}: operation ${attrs.operationId} ${attrs.status}${attrs.replacementKeyId ? ` (replacement ${attrs.replacementKeyId})` : ''}; check with \`saaslayer credentials status\``)
63
+ return attrs
64
+ }
65
+
66
+ module.exports = { credentialsStatus, credentialsRevoke, formatStatus }
@@ -29,7 +29,11 @@ async function status(flags) {
29
29
  for (const g of groups) {
30
30
  for (const i of g.instances || []) {
31
31
  const inst = i.deploymentInstance && i.deploymentInstance !== 'default' ? ` [${i.deploymentInstance}]` : ''
32
- console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst}`)
32
+ // release = the commit the instance was last deployed at; a fleet state other than ACTIVE (e.g. migrations
33
+ // awaiting approval) is shown because the deployment status alone reads ACTIVE.
34
+ const release = i.commitSha ? String(i.commitSha).slice(0, 8) : '—'
35
+ const fleet = i.fleetState && i.fleetState !== 'ACTIVE' ? ` ${i.fleetState}` : ''
36
+ console.log(` ${g.environment}/${i.region || '—'} ${i.status || '—'} ${i.deploymentId}${inst} release ${release}${fleet}`)
33
37
  }
34
38
  }
35
39
  return view
@@ -3,7 +3,7 @@
3
3
  'use strict'
4
4
  const readline = require('readline')
5
5
  const creds = require('../credentials')
6
- const { resolvePoolConfig, decodeJwt, controlPlaneUrl } = require('../config')
6
+ const { resolvePoolConfig, decodeJwt } = require('../config')
7
7
  const { discoverDeployment, discoverFromFlags } = require('../discovery')
8
8
 
9
9
  // Prompt for a value; hidden masks input (passwords). Only used when no flag/env supplies it.
@@ -219,26 +219,63 @@ async function loginDeployment(flags, deps = {}) {
219
219
  return { deploymentId, serviceInstance: profile.serviceInstance, environment, email: profile.email, userId: profile.userId }
220
220
  }
221
221
 
222
- // Create a SaaSLayer account via the control-plane signup endpoint (allowlist-gated), then log in.
223
- async function signup(flags = {}) {
224
- const base = String(controlPlaneUrl(flags).value).replace(/\/$/, '')
225
- const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
226
- const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Choose a password: ', { hidden: true }))
227
- const res = await fetch(`${base}/api/signup`, {
228
- method: 'POST',
229
- headers: { 'content-type': 'application/json' },
230
- body: JSON.stringify({ email, password }),
231
- })
232
- const doc = await res.json().catch(() => ({}))
233
- if (!res.ok) throw new Error(`signup failed (${res.status}): ${doc.error || JSON.stringify(doc)}`)
234
- // Log in immediately so the account is usable right away.
235
- return login({ ...flags, email, password })
222
+ /**
223
+ * @typedef {{ status: 'code-sent' | 'confirmed', email: string, next: string } | { status: 'logged-in', email: string, userId: string }} SignupOutcome
224
+ */
225
+
226
+ /**
227
+ * Create a SaaSLayer account against the control plane's login pool, the way the console does: Cognito SignUp (the
228
+ * pool's PreSignUp allowlist decides admission), then the code Cognito emailed confirms the account and proves the
229
+ * email. Then logs in. `--code` finishes a pending signup; `--resend` emails a new code. Without a terminal and no
230
+ * --code it stops after the code is sent and names the command that finishes it.
231
+ * @param {Record<string, any>} flags --email, --password, --code, --resend, --config-url
232
+ * @param {{ io?: LoginIo, login?: typeof login }} [deps]
233
+ * @returns {Promise<SignupOutcome>}
234
+ */
235
+ async function signup(flags = {}, deps = {}) {
236
+ const io = deps.io || terminalIo
237
+ const cognito = require('../cognito-user-api')
238
+ const pool = await resolvePoolConfig(flags)
239
+ const email = String(flags.email || process.env.SAASLAYER_EMAIL || (await io.prompt('Email: '))).trim().toLowerCase()
240
+ if (!email.includes('@')) throw new Error('signup requires a valid --email')
241
+ const finish = `saaslayer signup --email ${email} --code <code>`
242
+ let password = flags.password || process.env.SAASLAYER_PASSWORD
243
+ if (flags.resend) {
244
+ await cognito.resendConfirmationCode(pool, { email })
245
+ } else if (flags.code === undefined) {
246
+ if (!password) password = await io.prompt('Choose a password: ', { hidden: true })
247
+ try {
248
+ await cognito.signUp(pool, { email, password })
249
+ } catch (err) {
250
+ if (err.code === 'UsernameExistsException') throw new Error(`an account already exists for ${email}: log in with \`saaslayer login\`, or finish a pending signup with \`${finish}\` (\`--resend\` emails a new code)`)
251
+ if (err.code === 'UserLambdaValidationException') throw new Error(`signup refused: ${err.message}`)
252
+ throw err
253
+ }
254
+ }
255
+ if (flags.code === undefined && !io.isTTY) return { status: 'code-sent', email, next: `check ${email} for the code, then run: ${finish}` }
256
+ const code = flags.code !== undefined ? String(flags.code).trim() : String(await io.prompt(`Code emailed to ${email}: `)).trim()
257
+ try {
258
+ await cognito.confirmSignUp(pool, { email, code })
259
+ } catch (err) {
260
+ throw new Error(`signup not confirmed: ${err.message} Retry with \`${finish}\`, or email a new code with \`saaslayer signup --email ${email} --resend\``)
261
+ }
262
+ if (!password && io.isTTY) password = await io.prompt('Password: ', { hidden: true })
263
+ if (!password) return { status: 'confirmed', email, next: `account confirmed — run: saaslayer login --email ${email}` }
264
+ const who = await (deps.login || login)({ ...flags, email, password })
265
+ return { status: 'logged-in', email: who.email, userId: who.userId }
236
266
  }
237
267
 
268
+ /**
269
+ * The current control-plane account: its Cognito sub (userId), email, control plane, and its account id (custom:suid),
270
+ * the id an org owner adds members by.
271
+ * @returns {{ userId: string, email: string, env: string, accountId: string | null } | null}
272
+ */
238
273
  function whoami() {
239
274
  const current = creds.getCurrent()
240
275
  if (!current) return null
241
- return { userId: current.userId, email: current.email, env: current.env }
276
+ let accountId = null
277
+ try { accountId = decodeJwt(current.idToken)['custom:suid'] || null } catch { accountId = null }
278
+ return { userId: current.userId, email: current.email, env: current.env, accountId }
242
279
  }
243
280
 
244
281
  /**
@@ -0,0 +1,109 @@
1
+ // `saaslayer org members list|add|remove|set-role` — an org owner manages who belongs to the org and who deploys. Members
2
+ // are added by account id (`saaslayer whoami` prints it); the control plane refuses accounts whose email is not verified.
3
+ 'use strict'
4
+ const context = require('../context-store')
5
+ const { jsonApiCall } = require('../api-client')
6
+ const prompt = require('../prompt')
7
+
8
+ /**
9
+ * @typedef {{ userId: string, email?: string, owner?: boolean, deployer?: boolean }} MemberRow
10
+ * @typedef {{ ask?: (question: string) => Promise<string> }} ConfirmIo
11
+ */
12
+
13
+ /** @param {Record<string, any>} flags */
14
+ function orgOf(flags) {
15
+ const orgId = flags.org || context.get('org')
16
+ if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
17
+ return String(orgId)
18
+ }
19
+
20
+ /**
21
+ * The account id from --user or the positional argument.
22
+ * @param {Record<string, any>} flags
23
+ * @param {string | undefined} positional
24
+ * @param {string} usage the command, for the error
25
+ * @returns {string}
26
+ */
27
+ function accountOf(flags, positional, usage) {
28
+ const userId = flags.user || positional
29
+ if (!userId || typeof userId !== 'string') throw new Error(`${usage} needs the account id: --user <accountId> (the member finds it with \`saaslayer whoami\`)`)
30
+ return userId
31
+ }
32
+
33
+ const membersPath = (orgId) => `/api/orgs/${encodeURIComponent(orgId)}/members`
34
+
35
+ /** @param {MemberRow} m */
36
+ function roleOf(m) {
37
+ return m.owner ? 'owner' : m.deployer ? 'deployer' : 'member'
38
+ }
39
+
40
+ /**
41
+ * Print and return the org's members.
42
+ * @param {Record<string, any>} flags --org
43
+ * @returns {Promise<MemberRow[]>}
44
+ */
45
+ async function membersList(flags = {}) {
46
+ const orgId = orgOf(flags)
47
+ const doc = await jsonApiCall('GET', membersPath(orgId), undefined, flags)
48
+ /** @type {MemberRow[]} */
49
+ const rows = (doc.data || []).map((d) => d.attributes)
50
+ if (!rows.length) console.log(`no members in ${orgId}`)
51
+ for (const m of rows) console.log(`${m.userId} ${m.email || '—'} ${roleOf(m)}`)
52
+ return rows
53
+ }
54
+
55
+ /**
56
+ * Add an account to the org by its account id (`--role deployer` also lets it deploy). The control plane is asked first
57
+ * which account that id is; its email is shown and must be typed back unless --yes.
58
+ * @param {Record<string, any>} flags --org, --user, --role, --yes
59
+ * @param {ConfirmIo} [io]
60
+ * @param {string} [positional] the account id, when not given as --user
61
+ * @returns {Promise<{ userId: string, email: string, deployer: boolean } | null>} null when aborted
62
+ */
63
+ async function membersAdd(flags = {}, io = {}, positional) {
64
+ const userId = accountOf(flags, positional, 'org members add')
65
+ const role = flags.role
66
+ if (role !== undefined && role !== 'deployer') throw new Error('org members add: --role deployer is the only role an owner grants (omit it for a plain member)')
67
+ const orgId = orgOf(flags)
68
+ const attributes = { userId, ...(role ? { role } : {}) }
69
+ const preview = (await jsonApiCall('POST', membersPath(orgId), { data: { type: 'org-members', attributes: { ...attributes, dryRun: true } } }, flags)).data.attributes
70
+ console.log(`Adding ${preview.email} (${userId}) to org ${orgId}${role ? ' as a deployer' : ''}.`)
71
+ if (!flags.yes) {
72
+ const ask = io.ask || prompt.ask
73
+ const typed = await ask(`Type the account's email "${preview.email}" to confirm: `)
74
+ if (typed.trim().toLowerCase() !== String(preview.email).toLowerCase()) { console.log('Aborted (email did not match).'); return null }
75
+ }
76
+ const added = (await jsonApiCall('POST', membersPath(orgId), { data: { type: 'org-members', attributes } }, flags)).data.attributes
77
+ console.log(`✅ added ${added.email} (${userId}) to ${orgId}${added.deployer ? ' as a deployer' : ''}`)
78
+ return { userId, email: added.email, deployer: Boolean(added.deployer) }
79
+ }
80
+
81
+ /**
82
+ * Remove a member from the org (its deployer role is revoked first).
83
+ * @param {Record<string, any>} flags --org, --user
84
+ * @param {string} [positional]
85
+ */
86
+ async function membersRemove(flags = {}, positional) {
87
+ const userId = accountOf(flags, positional, 'org members remove')
88
+ const orgId = orgOf(flags)
89
+ await jsonApiCall('DELETE', `${membersPath(orgId)}/${encodeURIComponent(userId)}`, undefined, flags)
90
+ console.log(`✅ removed ${userId} from ${orgId}`)
91
+ return { userId, removed: true }
92
+ }
93
+
94
+ /**
95
+ * Make a member a deployer (`--role deployer`) or a plain member again (`--role member`).
96
+ * @param {Record<string, any>} flags --org, --user, --role
97
+ * @param {string} [positional]
98
+ */
99
+ async function membersSetRole(flags = {}, positional) {
100
+ const userId = accountOf(flags, positional, 'org members set-role')
101
+ if (flags.role !== 'deployer' && flags.role !== 'member') throw new Error('org members set-role needs --role deployer|member')
102
+ const orgId = orgOf(flags)
103
+ const path = `${membersPath(orgId)}/${encodeURIComponent(userId)}/roles/deployer`
104
+ await jsonApiCall(flags.role === 'deployer' ? 'POST' : 'DELETE', path, undefined, flags)
105
+ console.log(`✅ ${userId} is now a ${flags.role} of ${orgId}`)
106
+ return { userId, role: flags.role }
107
+ }
108
+
109
+ module.exports = { membersList, membersAdd, membersRemove, membersSetRole }
@@ -0,0 +1,172 @@
1
+ // `saaslayer permissions trust-policies list|get|add|update|disable|enable|delete`: the external login providers (OIDC issuers)
2
+ // a deployment trusts, through the permissions /trust-policies API. Policies made here are always external, never impersonating.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { permissionsRequest } = require('../permissions-request')
6
+
7
+ /**
8
+ * @typedef {import('../permissions-request').PermissionsFlags & { audience?: string|string[], subject?: string|string[],
9
+ * 'allow-any-subject'?: boolean, 'principal-claim'?: string, 'jwks-uri'?: string, description?: string, reason?: string }} TrustFlags
10
+ * @typedef {{ exchange?: typeof exchangeIamToken, ask?: (question: string) => Promise<string> }} Deps
11
+ */
12
+
13
+ // What the API's refusals mean for the person running the command.
14
+ const HINTS = {
15
+ FIRST_PARTY_POLICY: 'this policy is the deployment\'s own login pool (first-party); it is managed by the deployment, not through this command',
16
+ LAST_ADMIN_PROVIDER: 'this provider is the last sign-in path of every usable access admin; add another provider (or an admin who signs in elsewhere) first',
17
+ }
18
+
19
+ /** @param {string|string[]|undefined} v @returns {string[]|undefined} */
20
+ const listOf = (v) => (v === undefined ? undefined : Array.isArray(v) ? v : [v])
21
+
22
+ /** @param {string} label @param {string[]} positional @param {string} what */
23
+ function required(label, positional, what) {
24
+ if (!positional[0]) throw new Error(`${label}: <${what}> is required`)
25
+ return positional[0]
26
+ }
27
+
28
+ /**
29
+ * Call a trust-policies route; a refusal with a known code gains a hint.
30
+ * @param {string} label @param {TrustFlags} flags @param {Deps} deps @param {string} method @param {string} path @param {object} [body]
31
+ */
32
+ async function call(label, flags, deps, method, path, body) {
33
+ try {
34
+ return await permissionsRequest(label, flags, deps, method, path, body)
35
+ } catch (err) {
36
+ const hint = ((/** @type {{ codes?: string[] }} */ (err).codes) || []).map((c) => HINTS[/** @type {keyof typeof HINTS} */ (c)]).find(Boolean)
37
+ if (hint) err.message = `${err.message} — ${hint}`
38
+ throw err
39
+ }
40
+ }
41
+
42
+ /** @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
43
+ const policyOf = (body) => ({ id: body.data.id, ...body.data.attributes })
44
+
45
+ /**
46
+ * The subject rule: --subject (repeatable allowlist) or --allow-any-subject, never both.
47
+ * @param {string} label @param {TrustFlags} flags
48
+ * @returns {{ subjects?: string[], allowAnySubject?: boolean }}
49
+ */
50
+ function subjectRule(label, flags) {
51
+ const subjects = listOf(flags.subject)
52
+ if (subjects && flags['allow-any-subject']) throw new Error(`${label}: pass --subject S (repeatable) or --allow-any-subject, not both`)
53
+ if (subjects) return { subjects, allowAnySubject: false }
54
+ if (flags['allow-any-subject']) return { allowAnySubject: true }
55
+ return {}
56
+ }
57
+
58
+ /**
59
+ * The provider's OIDC discovery document; refuses unless its issuer is exactly the given one (tokens must match it exactly).
60
+ * @param {string} label @param {string} issuerUrl
61
+ * @returns {Promise<{ issuer: string, jwks_uri?: string }>}
62
+ */
63
+ async function providerConfiguration(label, issuerUrl) {
64
+ const url = `${issuerUrl.replace(/\/+$/, '')}/.well-known/openid-configuration`
65
+ /** @type {any} */
66
+ let config
67
+ try {
68
+ const res = await fetch(url, { method: 'GET', headers: { accept: 'application/json' } })
69
+ if (!res.ok) throw new Error(`${res.status}`)
70
+ config = await res.json()
71
+ } catch (err) {
72
+ throw new Error(`${label}: could not read ${url} (${err.message}) — is ${issuerUrl} an OIDC issuer?`)
73
+ }
74
+ if (!config || config.issuer !== issuerUrl) {
75
+ throw new Error(`${label}: ${url} says its issuer is "${config && config.issuer}", not "${issuerUrl}" — use the exact iss value the provider's ID tokens carry`)
76
+ }
77
+ return config
78
+ }
79
+
80
+ /** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
81
+ async function trustPoliciesList(positional, flags, deps = {}) {
82
+ const body = await call('permissions trust-policies list', flags, deps, 'GET', '/trust-policies')
83
+ return (body.data || []).map((/** @type {{ id: string, attributes: object }} */ d) => ({ id: d.id, ...d.attributes }))
84
+ }
85
+
86
+ /** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
87
+ async function trustPoliciesGet(positional, flags, deps = {}) {
88
+ const label = 'permissions trust-policies get'
89
+ const id = required(label, positional, 'policyId')
90
+ return policyOf(await call(label, flags, deps, 'GET', `/trust-policies/${encodeURIComponent(id)}`))
91
+ }
92
+
93
+ /**
94
+ * Trust an external login provider: <issuerUrl> --audience A [--audience B] (--subject S … | --allow-any-subject)
95
+ * [--principal-claim sub] [--jwks-uri URL] [--description D]. The issuer is checked against its openid-configuration.
96
+ * @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
97
+ */
98
+ async function trustPoliciesAdd(positional, flags, deps = {}) {
99
+ const label = 'permissions trust-policies add'
100
+ const issuerUrl = required(label, positional, 'issuerUrl')
101
+ if (!/^https:\/\//.test(issuerUrl)) throw new Error(`${label}: <issuerUrl> must be an https URL (the exact iss of the provider's ID tokens)`)
102
+ const audience = listOf(flags.audience)
103
+ if (!audience) throw new Error(`${label}: --audience <app client id> is required (repeatable)`)
104
+ const subjects = subjectRule(label, flags)
105
+ if (subjects.allowAnySubject === undefined) throw new Error(`${label}: pass --subject S (repeatable) or --allow-any-subject — a policy with neither authorizes nobody`)
106
+ const config = await providerConfiguration(label, issuerUrl)
107
+ const jwksUri = flags['jwks-uri'] || config.jwks_uri
108
+ const request = {
109
+ issuerUrl,
110
+ audience,
111
+ ...(jwksUri ? { jwksUri } : {}),
112
+ claimMapping: { principalId: flags['principal-claim'] || 'sub' },
113
+ ...subjects,
114
+ ...(flags.description ? { description: flags.description } : {}),
115
+ external: true,
116
+ allowImpersonation: false,
117
+ }
118
+ return policyOf(await call(label, flags, deps, 'POST', '/trust-policies', request))
119
+ }
120
+
121
+ /**
122
+ * Change a provider's audience, subject rule, JWKS URI or description. The issuer and principal claim never change (they key
123
+ * every principal the provider signs in).
124
+ * @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
125
+ */
126
+ async function trustPoliciesUpdate(positional, flags, deps = {}) {
127
+ const label = 'permissions trust-policies update'
128
+ const id = required(label, positional, 'policyId')
129
+ if (flags['principal-claim'] !== undefined) throw new Error(`${label}: --principal-claim cannot change — it keys every principal this provider signs in; add a new provider instead`)
130
+ const audience = listOf(flags.audience)
131
+ const patch = {
132
+ ...(audience ? { audience } : {}),
133
+ ...(flags['jwks-uri'] ? { jwksUri: flags['jwks-uri'] } : {}),
134
+ ...(flags.description !== undefined ? { description: String(flags.description) } : {}),
135
+ ...subjectRule(label, flags),
136
+ }
137
+ if (Object.keys(patch).length === 0) throw new Error(`${label}: nothing to update — give --audience, --subject, --allow-any-subject, --jwks-uri or --description`)
138
+ return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, patch))
139
+ }
140
+
141
+ /** Stop trusting a provider without deleting it. @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
142
+ async function trustPoliciesDisable(positional, flags, deps = {}) {
143
+ const label = 'permissions trust-policies disable'
144
+ const id = required(label, positional, 'policyId')
145
+ return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, { enabled: false }))
146
+ }
147
+
148
+ /** @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps] */
149
+ async function trustPoliciesEnable(positional, flags, deps = {}) {
150
+ const label = 'permissions trust-policies enable'
151
+ const id = required(label, positional, 'policyId')
152
+ return policyOf(await call(label, flags, deps, 'PUT', `/trust-policies/${encodeURIComponent(id)}`, { enabled: true }))
153
+ }
154
+
155
+ /**
156
+ * Delete a provider: --reason, then its issuer typed to confirm (--yes confirms). Its people can no longer sign in.
157
+ * @param {string[]} positional @param {TrustFlags} flags @param {Deps} [deps]
158
+ */
159
+ async function trustPoliciesDelete(positional, flags, deps = {}) {
160
+ const label = 'permissions trust-policies delete'
161
+ const id = required(label, positional, 'policyId')
162
+ if (!flags.reason || typeof flags.reason !== 'string') throw new Error(`${label}: --reason <text> is required`)
163
+ const path = `/trust-policies/${encodeURIComponent(id)}`
164
+ const policy = policyOf(await call(label, flags, deps, 'GET', path))
165
+ const issuer = String(policy.issuerUrl)
166
+ const ask = deps.ask || require('../prompt').ask
167
+ const typed = flags.yes ? issuer : await ask(`Delete trust in ${issuer}? Everyone who signs in through it loses access. Type the issuer "${issuer}" to confirm: `)
168
+ if (typed !== issuer) throw new Error(`${label}: not confirmed — nothing deleted`)
169
+ return policyOf(await call(label, flags, deps, 'DELETE', path, { reason: flags.reason }))
170
+ }
171
+
172
+ module.exports = { trustPoliciesList, trustPoliciesGet, trustPoliciesAdd, trustPoliciesUpdate, trustPoliciesDisable, trustPoliciesEnable, trustPoliciesDelete }