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.
Files changed (48) hide show
  1. package/README.md +150 -13
  2. package/bin/saaslayer.js +318 -66
  3. package/package.json +4 -3
  4. package/src/api-client.js +48 -28
  5. package/src/aws-sigv4.js +1 -1
  6. package/src/commands/access-admins.js +73 -0
  7. package/src/commands/accounts.js +32 -3
  8. package/src/commands/activity.js +33 -0
  9. package/src/commands/aws.js +55 -6
  10. package/src/commands/catalog.js +30 -29
  11. package/src/commands/context.js +64 -0
  12. package/src/commands/deploy.js +79 -10
  13. package/src/commands/first-admin.js +42 -0
  14. package/src/commands/foundation.js +456 -0
  15. package/src/commands/integration-credentials.js +66 -0
  16. package/src/commands/lifecycle.js +77 -40
  17. package/src/commands/login.js +200 -26
  18. package/src/commands/machine-trust.js +96 -0
  19. package/src/commands/operations.js +140 -0
  20. package/src/commands/orgs.js +29 -4
  21. package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
  22. package/src/commands/release-manifest.js +138 -0
  23. package/src/commands/service-principals.js +81 -0
  24. package/src/commands/settings.js +140 -0
  25. package/src/commands/stacks.js +12 -7
  26. package/src/commands/users-management.js +401 -0
  27. package/src/commands/users.js +192 -4
  28. package/src/config.js +20 -7
  29. package/src/credentials.js +221 -34
  30. package/src/deployment-api-auth.js +61 -0
  31. package/src/deployment-auth.js +38 -0
  32. package/src/deployments.js +12 -13
  33. package/src/discovery.js +66 -0
  34. package/src/env-compare.js +143 -0
  35. package/src/iam-session.js +4 -30
  36. package/src/module-catalog.js +66 -0
  37. package/src/permissions-request.js +43 -0
  38. package/src/release-manifest.js +334 -0
  39. package/src/scope.js +114 -0
  40. package/src/settings.js +272 -0
  41. package/src/users-api.js +165 -0
  42. package/src/users-import/import.js +10 -10
  43. package/templates/saaslayer-foundation-region.yml +37 -1
  44. package/templates/saaslayer-foundation.yml +63 -10
  45. package/src/commands/iam-principals.js +0 -53
  46. package/src/rbac-auth.js +0 -25
  47. package/vendor/ids/index.d.ts +0 -21
  48. package/vendor/ids/index.js +0 -237
@@ -0,0 +1,140 @@
1
+ // `saaslayer operations get|watch|cancel <id>` and the --wait every mutating command runs: follow an operation (a deployment
2
+ // run) to its terminal state, print each component's outcome, and fail with the next supported command; cancel an
3
+ // in-flight one (needs saaslayer:deployer:deployment:cancel-run).
4
+ 'use strict'
5
+ const crypto = require('crypto')
6
+ const path = require('path')
7
+ const { apiCall } = require('../api-client')
8
+ const { resolveDeployment } = require('../deployments')
9
+
10
+ // The monorepo source, for running the CLI from a checkout before vendor/ is synced (the published package carries
11
+ // vendor/operations, synced on prepack).
12
+ const MONOREPO_OPERATIONS = path.join(__dirname, '../../../operations/src')
13
+
14
+ /** A module of the operations package (index by default; activity for the activity feed). @param {string} [file] */
15
+ function loadOperations(file = 'index') {
16
+ try {
17
+ return require(`../../vendor/operations/${file}`)
18
+ } catch (err) {
19
+ if (err && err.code !== 'MODULE_NOT_FOUND') throw err
20
+ return require(path.join(MONOREPO_OPERATIONS, file))
21
+ }
22
+ }
23
+
24
+ const USAGE = 'usage: saaslayer operations <get|watch|cancel> <operationId> [--deployment ID | --project P --env E --region R] [--json] [--interval SECONDS] [--reason TEXT]'
25
+
26
+ /** A fresh request key per CLI invocation: a retry of this invocation replays its operation, a new invocation does not. */
27
+ function requestKeyHeaders() {
28
+ return { 'Idempotency-Key': `cli-${crypto.randomUUID()}` }
29
+ }
30
+
31
+ /**
32
+ * @param {string} operationId
33
+ * @param {string} deploymentId
34
+ */
35
+ function resumeCommand(operationId, deploymentId) {
36
+ return `saaslayer operations watch ${operationId} --deployment ${deploymentId}`
37
+ }
38
+
39
+ /** Seconds between polls (--interval), default 5. @param {object} flags */
40
+ function intervalMs(flags) {
41
+ const seconds = flags.interval === undefined ? 5 : Number(flags.interval)
42
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : 5000
43
+ }
44
+
45
+ /**
46
+ * Read an operation. A 4xx other than 408/429 is fatal (no retry); anything else is a transient fault for the watcher.
47
+ * @param {string} deploymentId
48
+ * @param {string} operationId
49
+ * @param {object} flags
50
+ */
51
+ async function fetchOperation(deploymentId, operationId, flags) {
52
+ try {
53
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}/operations/${encodeURIComponent(operationId)}`, undefined, flags)
54
+ return loadOperations().redact(doc.data.attributes)
55
+ } catch (err) {
56
+ const status = err && err.status
57
+ if (status >= 400 && status < 500 && status !== 408 && status !== 429) err.fatal = true
58
+ throw err
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Wait for an operation to finish. Succeeded: prints its components and returns it. Failed or partial: throws an
64
+ * error whose message lists each component's outcome and the next supported command.
65
+ * @param {{ deploymentId: string, operationId: string, flags: object }} input
66
+ */
67
+ async function followOperation({ deploymentId, operationId, flags }) {
68
+ const ops = loadOperations()
69
+ const final = await ops.watchOperation({
70
+ id: operationId,
71
+ fetchOperation: () => fetchOperation(deploymentId, operationId, flags),
72
+ intervalMs: intervalMs(flags),
73
+ onUpdate: (op) => { if (!ops.isTerminal(op.status)) console.log(` … operation ${op.id}: ${op.status}`) },
74
+ resumeCommand: resumeCommand(operationId, deploymentId),
75
+ })
76
+ const lines = ops.formatOperation(final)
77
+ if (final.status === 'succeeded') {
78
+ console.log(lines.join('\n'))
79
+ return final
80
+ }
81
+ throw Object.assign(new Error(lines.join('\n')), { operation: final })
82
+ }
83
+
84
+ /**
85
+ * After a mutating command is accepted: wait for its operation (default) or, with --no-wait, print how to follow it.
86
+ * Attaches the finished operation to the response it returns.
87
+ * @param {{ response: { data?: { attributes?: Record<string, unknown> } } & Record<string, unknown>, deploymentId: string, flags: object }} input
88
+ */
89
+ async function finishMutation({ response, deploymentId, flags }) {
90
+ const attrs = (response && response.data && response.data.attributes) || {}
91
+ const operationId = typeof attrs.operationId === 'string' ? attrs.operationId : null
92
+ if (!operationId) return response
93
+ if (flags['no-wait'] === true || flags['no-wait'] === 'true') {
94
+ console.log(` follow: ${resumeCommand(operationId, deploymentId)}`)
95
+ return response
96
+ }
97
+ console.log(` waiting for operation ${operationId} (--no-wait to return now; resume with: ${resumeCommand(operationId, deploymentId)})`)
98
+ response.operation = await followOperation({ deploymentId, operationId, flags })
99
+ return response
100
+ }
101
+
102
+ /**
103
+ * Cancel an in-flight operation: the deployer stops its execution and releases the deployment's run lock, and the
104
+ * deployment's activity records the cancel with the caller and --reason.
105
+ * @param {string} deploymentId
106
+ * @param {string} operationId
107
+ * @param {object} flags
108
+ * @returns {Promise<{ deploymentId: string, operationId: string, status: string }>}
109
+ */
110
+ async function cancelOperation(deploymentId, operationId, flags) {
111
+ const reason = typeof flags.reason === 'string' && flags.reason.trim() ? flags.reason.trim() : null
112
+ const body = reason ? { data: { type: 'operation-cancellations', attributes: { reason } } } : undefined
113
+ const doc = await apiCall('POST', `/api/deployments/${encodeURIComponent(deploymentId)}/operations/${encodeURIComponent(operationId)}/cancel`, body, flags)
114
+ const result = doc.data.attributes
115
+ if (flags.json) {
116
+ console.log(JSON.stringify(result, null, 2))
117
+ } else {
118
+ console.log(`cancelled operation ${operationId} on deployment ${deploymentId} (${result.status})`)
119
+ console.log(` check: saaslayer operations get ${operationId} --deployment ${deploymentId}`)
120
+ }
121
+ return result
122
+ }
123
+
124
+ /**
125
+ * `saaslayer operations get|watch|cancel <id>`.
126
+ * @param {string|undefined} sub
127
+ * @param {string|undefined} operationId
128
+ * @param {object} flags
129
+ */
130
+ async function operationsCommand(sub, operationId, flags) {
131
+ if (!['get', 'watch', 'cancel'].includes(sub) || !operationId) throw new Error(USAGE)
132
+ const deploymentId = flags.deployment || (await resolveDeployment(flags)).deploymentId
133
+ if (sub === 'cancel') return cancelOperation(deploymentId, operationId, flags)
134
+ if (sub === 'watch') return followOperation({ deploymentId, operationId, flags })
135
+ const op = await fetchOperation(deploymentId, operationId, flags)
136
+ console.log(flags.json ? JSON.stringify(op, null, 2) : loadOperations().formatOperation(op).join('\n'))
137
+ return op
138
+ }
139
+
140
+ module.exports = { operationsCommand, finishMutation, followOperation, requestKeyHeaders, resumeCommand, loadOperations, intervalMs }
@@ -1,9 +1,10 @@
1
- // `saaslayer org …` and `saaslayer project …` — create/list orgs and projects against the SaaSLayer
2
- // control-plane API, authenticated with the cached Cognito id token (Bearer). The active org is
3
- // remembered locally so `project create` doesn't need --org each time.
1
+ // `saaslayer org …` and `saaslayer project …` — create/list orgs and projects, and destroy a project whose deployments
2
+ // are gone, against the SaaSLayer control-plane API, authenticated with the cached Cognito id token (Bearer). The active
3
+ // org is remembered locally so `project create` doesn't need --org each time.
4
4
  'use strict'
5
5
  const context = require('../context-store')
6
6
  const { apiCall } = require('../api-client')
7
+ const prompt = require('../prompt')
7
8
 
8
9
  async function orgCreate(flags, name) {
9
10
  if (!name) throw new Error('org create requires a name')
@@ -53,4 +54,28 @@ async function projectList(flags) {
53
54
  return doc.projects || []
54
55
  }
55
56
 
56
- module.exports = { orgCreate, orgList, orgUse, projectCreate, projectList }
57
+ /**
58
+ * `saaslayer project destroy [<id>] [--yes]`: delete a project (the active one by default) and release its public name.
59
+ * The control plane refuses while any deployment of it is live; destroy each with `saaslayer destroy` first. Needs
60
+ * saaslayer:deployer:project:delete. Asks for the project id to be typed unless --yes.
61
+ * @param {object} flags
62
+ * @param {string} [projectId]
63
+ * @param {{ ask?: (question: string) => Promise<string> }} [io] the confirmation prompt (tests pass their own)
64
+ * @returns {Promise<{ id: string, destroyed: boolean, releasedSlugs: string[], notOwnedSlugs: string[] } | null>} null when aborted
65
+ */
66
+ async function projectDestroy(flags, projectId, io = {}) {
67
+ const id = projectId || context.get('project')
68
+ if (!id) throw new Error('project destroy requires a project id (or an active project: `saaslayer project use <id>`)')
69
+ console.log(`⚠ This will DESTROY project ${id} and release its public name. Its deployments must already be destroyed.`)
70
+ const ask = io.ask || prompt.ask
71
+ const typed = flags.yes ? id : await ask(`Type the project id "${id}" to confirm: `)
72
+ if (typed !== id) { console.log('Aborted (id did not match).'); return null }
73
+ const result = await apiCall('DELETE', `/api/projects/${encodeURIComponent(id)}`, undefined, flags)
74
+ const released = (result.releasedSlugs || []).map((s) => `'${s}'`).join(', ')
75
+ console.log(`✅ destroyed project ${id}${released ? `; released ${released}` : ''}`)
76
+ if ((result.notOwnedSlugs || []).length) console.log(` held by another project, left alone: ${result.notOwnedSlugs.join(', ')}`)
77
+ if (context.get('project') === id) context.set('project', null)
78
+ return result
79
+ }
80
+
81
+ module.exports = { orgCreate, orgList, orgUse, projectCreate, projectList, projectDestroy }
@@ -1,8 +1,8 @@
1
- // `saaslayer rbac inspect <type>:<id> | session:<id>`: a principal's permissions from the terminal (expanded view with
1
+ // `saaslayer permissions inspect <type>:<id> | session:<id>`: a principal's permissions from the terminal (expanded view with
2
2
  // independent scope/assignment paging, or the stored inspection model) — never parses the compact stored schema.
3
3
  'use strict'
4
4
  const { exchangeIamToken } = require('../iam-session')
5
- const { authHeaders } = require('../rbac-auth')
5
+ const { authHeaders } = require('../deployment-api-auth')
6
6
 
7
7
  const USAGE = '<principalType>:<id> or session:<id> (e.g. USER:alice, SERVICE_ACCOUNT:svc-1)'
8
8
 
@@ -22,7 +22,7 @@ function parseRef(raw) {
22
22
  const at = s.indexOf(':')
23
23
  const type = at > 0 ? s.slice(0, at) : ''
24
24
  const id = at > 0 ? s.slice(at + 1) : ''
25
- if (!type || !id) throw new Error(`rbac inspect: expected ${USAGE}`)
25
+ if (!type || !id) throw new Error(`permissions inspect: expected ${USAGE}`)
26
26
  if (type.toLowerCase() === 'session') return { kind: 'session', id }
27
27
  return { kind: 'principal', type: type.toUpperCase(), id }
28
28
  }
@@ -104,8 +104,8 @@ function formatExpanded(view, { ref, inspection }) {
104
104
  if (scopes.length) for (const scope of scopes) out.push(bucketBlock(`Scope ${scope}`, view.scoped[scope]))
105
105
  else out.push('(no scopes on this page)')
106
106
  const hints = []
107
- if (meta.nextScopeCursor) hints.push(`more scopes: saaslayer rbac inspect ${ref} --scope-page ${meta.nextScopeCursor}`)
108
- if (meta.nextAssignmentCursor) hints.push(`more assignments: saaslayer rbac inspect ${ref} --assignment-page ${meta.nextAssignmentCursor}`)
107
+ if (meta.nextScopeCursor) hints.push(`more scopes: saaslayer permissions inspect ${ref} --scope-page ${meta.nextScopeCursor}`)
108
+ if (meta.nextAssignmentCursor) hints.push(`more assignments: saaslayer permissions inspect ${ref} --assignment-page ${meta.nextAssignmentCursor}`)
109
109
  if (hints.length) out.push('', ...hints)
110
110
  return out.join('\n')
111
111
  }
@@ -145,11 +145,11 @@ async function getAttributes(url, headers, ref) {
145
145
  if (res.ok) return body.data.attributes
146
146
  const first = (body.errors && body.errors[0]) || {}
147
147
  const detail = first.message || first.detail || res.statusText || ''
148
- if (res.status === 401) throw Object.assign(new Error(`rbac inspect: not authenticated (401) — check --token / --iam`), { status: 401 })
149
- if (res.status === 403) throw Object.assign(new Error(`rbac inspect: forbidden (403) — needs saaslayer:principals authority over ${ref}: ${detail}`), { status: 403 })
150
- if (res.status === 404) throw Object.assign(new Error(`rbac inspect: ${ref} not found (404) — or you have no saaslayer:principals authority where it lives`), { status: 404 })
151
- if (res.status === 409) throw Object.assign(new Error(`rbac inspect: the doc changed while paging (409 PermissionDocChanged) — restart without a page cursor`), { status: 409 })
152
- throw Object.assign(new Error(`rbac inspect failed (${res.status}): ${detail}`), { status: res.status })
148
+ if (res.status === 401) throw Object.assign(new Error(`permissions inspect: not authenticated (401) — check --token / --iam`), { status: 401 })
149
+ if (res.status === 403) throw Object.assign(new Error(`permissions inspect: forbidden (403) — needs saaslayer:identity authority over ${ref}: ${detail}`), { status: 403 })
150
+ if (res.status === 404) throw Object.assign(new Error(`permissions inspect: ${ref} not found (404) — or you have no saaslayer:identity authority where it lives`), { status: 404 })
151
+ if (res.status === 409) throw Object.assign(new Error(`permissions inspect: the doc changed while paging (409 PermissionDocChanged) — restart without a page cursor`), { status: 409 })
152
+ throw Object.assign(new Error(`permissions inspect failed (${res.status}): ${detail}`), { status: res.status })
153
153
  }
154
154
 
155
155
  /**
@@ -159,11 +159,11 @@ async function getAttributes(url, headers, ref) {
159
159
  * @param {{ exchange?: typeof exchangeIamToken, print?: (s: string) => void }} [deps]
160
160
  * @returns {Promise<string>} what was printed
161
161
  */
162
- async function rbacInspect(positional, flags, deps = {}) {
162
+ async function permissionsInspect(positional, flags, deps = {}) {
163
163
  const ref = parseRef(positional[0])
164
164
  const refText = ref.kind === 'session' ? `session:${ref.id}` : `${ref.type}:${ref.id}`
165
165
  const apiBase = String(flags['api-base'] || process.env.SAASLAYER_API_BASE || '').replace(/\/$/, '')
166
- if (!apiBase) throw new Error('rbac inspect: --api-base (or $SAASLAYER_API_BASE) is required')
166
+ if (!apiBase) throw new Error('permissions inspect: --api-base (or $SAASLAYER_API_BASE) is required')
167
167
  const headers = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
168
168
  const print = deps.print || ((/** @type {string} */ s) => console.log(s))
169
169
  const emit = (/** @type {string} */ s) => { print(s); return s }
@@ -219,10 +219,10 @@ async function rbacInspect(positional, flags, deps = {}) {
219
219
  return emit(formatExpanded(view, { ref: refText, inspection: stored.inspection }))
220
220
  } catch (err) {
221
221
  if (/** @type {any} */ (err).status !== 409 || attempt === 1) throw err
222
- console.error('rbac inspect: the doc was rebuilt while paging (409) — restarting from the first page')
222
+ console.error('permissions inspect: the doc was rebuilt while paging (409) — restarting from the first page')
223
223
  }
224
224
  }
225
- throw new Error('rbac inspect: unreachable')
225
+ throw new Error('permissions inspect: unreachable')
226
226
  }
227
227
 
228
- module.exports = { rbacInspect, parseRef, formatExpanded, formatInspection, formatSize }
228
+ module.exports = { permissionsInspect, parseRef, formatExpanded, formatInspection, formatSize }
@@ -0,0 +1,138 @@
1
+ // `saaslayer update --manifest FILE` (preflight, then move the release through /update and write the environment's
2
+ // settings through the settings route) and `saaslayer release-manifest create` (record a tested deployment's release).
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const { apiCall } = require('../api-client')
6
+ const { finishMutation, requestKeyHeaders } = require('./operations')
7
+ const { applySettings, fetchSchema, readDeploymentSettings } = require('./settings')
8
+ const { formatChanges } = require('../settings')
9
+ const rm = require('../release-manifest')
10
+ const { version: CLI_VERSION } = require('../../package.json')
11
+
12
+ const USAGE = 'usage: saaslayer release-manifest create --env E [--out FILE] [--name NAME] (see saaslayer --help)'
13
+
14
+ /** @param {object} flags @param {string} name */
15
+ const flagOn = (flags, name) => flags[name] === true || flags[name] === 'true'
16
+
17
+ /**
18
+ * Each bundle module's contract at the bundle revision, or the error code that kept it out.
19
+ * @param {rm.ReleaseManifest} manifest @param {object} flags
20
+ * @returns {Promise<Record<string, { schema?: import('../settings').SettingsSchema, error?: string }>>}
21
+ */
22
+ async function fetchTargetSchemas(manifest, flags) {
23
+ const entries = await Promise.all(Object.keys(manifest.bundle.modules).map(async (module) => {
24
+ try {
25
+ return [module, { schema: await fetchSchema(module, manifest.bundle.revision, flags) }]
26
+ } catch (err) {
27
+ if (!err.status || err.status >= 500) throw err
28
+ const code = err.body && err.body.errors && err.body.errors[0] && err.body.errors[0].code
29
+ return [module, { error: code || `HTTP ${err.status}` }]
30
+ }
31
+ }))
32
+ return Object.fromEntries(entries)
33
+ }
34
+
35
+ /**
36
+ * `update --manifest FILE [--env E] [--settings F] [--reason T] [--force] [--dry-run] [--no-wait]`. Refuses on any
37
+ * preflight problem before anything is sent.
38
+ * @param {object} flags
39
+ */
40
+ async function updateFromManifest(flags) {
41
+ if (flags['commit-sha'] !== undefined || flags.commitSha !== undefined || flags.param !== undefined) {
42
+ throw new Error('--manifest sets the release and settings: drop --commit-sha and --param')
43
+ }
44
+ const file = flags.manifest
45
+ if (typeof file !== 'string') throw new Error('update --manifest needs a release manifest file')
46
+ const manifest = rm.readManifest(file)
47
+ const { deployment, settings } = await readDeploymentSettings(flags)
48
+ const env = deployment.env
49
+ const envPatch = rm.environmentSettings(manifest, file, env, flags.settings)
50
+ const result = rm.preflightManifest({
51
+ manifest,
52
+ env,
53
+ current: settings,
54
+ targetSchemas: await fetchTargetSchemas(manifest, flags),
55
+ envPatch,
56
+ reason: typeof flags.reason === 'string' ? flags.reason : undefined,
57
+ cliVersion: CLI_VERSION,
58
+ noWait: flagOn(flags, 'no-wait'),
59
+ })
60
+ const target = manifest.bundle.revision
61
+ const where = `${env} (${deployment.deploymentId})`
62
+ if (!result.ok) {
63
+ const lines = result.problems.map((p) => ` - ${p.code}: ${p.message}${p.action ? `\n → ${p.action}` : ''}`)
64
+ throw new Error(`preflight ${where} failed — nothing was changed:\n${lines.join('\n')}`)
65
+ }
66
+ console.log(`preflight ${where}: ok${manifest.name ? ` (${manifest.name})` : ''}`)
67
+ console.log(` release: ${result.fromRevisions.map((r) => r.slice(0, 7)).join(', ')} → ${target.slice(0, 7)}${result.moveRelease ? '' : ' (already deployed)'}`)
68
+ if (result.patch) for (const line of formatChanges(result.patch, settings)) console.log(line)
69
+ else console.log(` settings: ${envPatch ? 'match' : `none named for ${env}`}`)
70
+ if (flagOn(flags, 'dry-run')) {
71
+ console.log('[dry-run] nothing was changed')
72
+ return result
73
+ }
74
+ if (!result.moveRelease && !result.patch) {
75
+ console.log(`${deployment.deploymentId} already runs ${target.slice(0, 7)} and its settings match: nothing to change`)
76
+ return result
77
+ }
78
+ if (result.moveRelease) {
79
+ const attributes = { commitSha: target }
80
+ if (flags.reason) attributes.reason = flags.reason
81
+ if (flagOn(flags, 'force')) attributes.force = true
82
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/update`, { data: { type: 'deployments', attributes } }, flags, { headers: requestKeyHeaders() })
83
+ console.log(`✅ release move to ${target.slice(0, 7)} started for ${deployment.deploymentId}`)
84
+ await finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
85
+ }
86
+ if (result.patch) await applySettings(result.patch, flags)
87
+ return result
88
+ }
89
+
90
+ /**
91
+ * `release-manifest create --env E [--out FILE] [--name NAME]`: the revision, settings-contract hashes and permissions writer
92
+ * declaration of a tested deployment, and this CLI's version. Reader declarations and environment settings are left
93
+ * for the author: a missing reader declaration is never inferred.
94
+ * @param {object} flags
95
+ */
96
+ async function createManifest(flags) {
97
+ const { deployment, settings } = await readDeploymentSettings(flags)
98
+ const revisions = [...new Set(settings.modules.map((m) => m.revision))]
99
+ if (revisions.length !== 1 || !revisions[0]) {
100
+ throw new Error(`${deployment.deploymentId} runs more than one revision (${settings.modules.map((m) => `${m.module}@${(m.revision || '—').slice(0, 7)}`).join(', ')}): update it to one tested release first`)
101
+ }
102
+ const revision = /** @type {string} */ (revisions[0])
103
+ /** @type {Record<string, { settingsContractSha256: string }>} */
104
+ const modules = {}
105
+ for (const m of settings.modules) modules[m.module] = { settingsContractSha256: rm.contractHash(await fetchSchema(m.module, revision, flags)) }
106
+ const writer = settings.modules.find((m) => m.module === rm.PERMISSIONS_WRITER.module)
107
+ const docSetting = writer && writer.settings.find((s) => s.name === rm.PERMISSIONS_WRITER.permissionDocSetting)
108
+ const manifest = {
109
+ schemaVersion: rm.MANIFEST_SCHEMA_VERSION,
110
+ ...(typeof flags.name === 'string' ? { name: flags.name } : {}),
111
+ bundle: { revision, modules },
112
+ tooling: { cli: CLI_VERSION },
113
+ ...(writer ? { compatibility: { permissions: rm.permissionsWriterRelease(docSetting ? docSetting.value : undefined) } } : {}),
114
+ environments: {},
115
+ }
116
+ const { problems } = rm.validateManifest(manifest)
117
+ if (problems.length) throw new Error(`release manifest for ${deployment.deploymentId} is invalid:\n${problems.map((p) => ` - ${p}`).join('\n')}`)
118
+ const text = `${JSON.stringify(manifest, null, 2)}\n`
119
+ if (typeof flags.out === 'string') {
120
+ fs.writeFileSync(flags.out, text)
121
+ console.log(`release manifest for ${deployment.deploymentId} @ ${revision.slice(0, 7)} written to ${flags.out}`)
122
+ } else {
123
+ console.log(text)
124
+ }
125
+ if (writer) console.log('next: add permissionsDirectMode.readers (an empty list when no app reads the permissions table directly) and environments.<env>.settings')
126
+ return manifest
127
+ }
128
+
129
+ /**
130
+ * @param {string|undefined} sub
131
+ * @param {object} flags
132
+ */
133
+ async function releaseManifestCommand(sub, flags) {
134
+ if (sub === 'create') return createManifest(flags)
135
+ throw new Error(USAGE)
136
+ }
137
+
138
+ module.exports = { updateFromManifest, releaseManifestCommand }
@@ -0,0 +1,81 @@
1
+ // `saaslayer permissions service-principal roles|assign|unassign`: typed role assignment for service principals (matrix R10)
2
+ // — a declared IAM machine's mapped principal (--machine <principalId> → iam.<principalId>) or any service account id.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { authHeaders } = require('../deployment-api-auth')
6
+
7
+ /**
8
+ * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, machine?: string, role?: string, scope?: string }} ServicePrincipalFlags
9
+ */
10
+
11
+ /**
12
+ * The service principal id from the positional id or --machine, and the permissions API base.
13
+ * @param {string} label @param {string[]} positional @param {ServicePrincipalFlags} flags
14
+ * @returns {{ id: string, apiBase: string }}
15
+ */
16
+ function target(label, positional, flags) {
17
+ const id = flags.machine ? `iam.${flags.machine}` : positional[0]
18
+ if (!id) throw new Error(`${label}: a service principal id or --machine <principalId> is required`)
19
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
20
+ if (!apiBase) throw new Error(`${label}: --api-base (or $SAASLAYER_API_BASE) is required`)
21
+ return { id, apiBase: apiBase.replace(/\/$/, '') }
22
+ }
23
+
24
+ /**
25
+ * Call the typed assignment route; throws with the API's error messages.
26
+ * @param {string} label @param {string} url @param {RequestInit} init
27
+ */
28
+ async function call(label, url, init) {
29
+ const res = await fetch(url, init)
30
+ const body = res.status === 204 ? null : await res.json().catch(() => ({}))
31
+ if (!res.ok) {
32
+ const detail = ((body && body.errors) || []).map((e) => e.message || e.detail).filter(Boolean).join('; ') || JSON.stringify(body)
33
+ throw new Error(`${label} failed (${res.status}): ${detail}`)
34
+ }
35
+ return body
36
+ }
37
+
38
+ /**
39
+ * A service principal's role assignments.
40
+ * @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
41
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
42
+ * @returns {Promise<Array<{ roleId: string, scope: string|null }>>}
43
+ */
44
+ async function servicePrincipalRoles(positional, flags, deps = {}) {
45
+ const { id, apiBase } = target('permissions service-principal roles', positional, flags)
46
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
47
+ const body = await call('permissions service-principal roles', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles`, { method: 'GET', headers: auth })
48
+ return (body.data || []).map((d) => d.attributes)
49
+ }
50
+
51
+ /**
52
+ * Grant a role (--role) to a service principal, deployment-wide unless --scope names an org scope.
53
+ * @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
54
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
55
+ */
56
+ async function servicePrincipalAssign(positional, flags, deps = {}) {
57
+ const { id, apiBase } = target('permissions service-principal assign', positional, flags)
58
+ if (!flags.role) throw new Error('permissions service-principal assign: --role <roleId> is required')
59
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
60
+ const body = await call('permissions service-principal assign', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles`, {
61
+ method: 'POST',
62
+ headers: { ...auth, 'content-type': 'application/json' },
63
+ body: JSON.stringify({ roleId: flags.role, ...(flags.scope ? { scope: flags.scope } : {}) }),
64
+ })
65
+ return body.data.attributes
66
+ }
67
+
68
+ /**
69
+ * Revoke a role (--role, at --scope if given) from a service principal.
70
+ * @param {string[]} positional [servicePrincipalId] @param {ServicePrincipalFlags} flags
71
+ * @param {{ exchange?: typeof exchangeIamToken }} [deps]
72
+ */
73
+ async function servicePrincipalUnassign(positional, flags, deps = {}) {
74
+ const { id, apiBase } = target('permissions service-principal unassign', positional, flags)
75
+ if (!flags.role) throw new Error('permissions service-principal unassign: --role <roleId> is required')
76
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
77
+ const qs = flags.scope ? `?scope=${encodeURIComponent(flags.scope)}` : ''
78
+ await call('permissions service-principal unassign', `${apiBase}/principals/serviceAccount/${encodeURIComponent(id)}/roles/${encodeURIComponent(flags.role)}${qs}`, { method: 'DELETE', headers: auth })
79
+ }
80
+
81
+ module.exports = { servicePrincipalRoles, servicePrincipalAssign, servicePrincipalUnassign }
@@ -0,0 +1,140 @@
1
+ // `saaslayer settings schema|get|set|diff` — read a module's published settings schema, read a deployment's settings,
2
+ // write a schema-checked patch through PATCH /api/deployments/{id}/settings (then wait for its operation), and compare envs.
3
+ 'use strict'
4
+ const { apiCall } = require('../api-client')
5
+ const { resolveDeployment } = require('../deployments')
6
+ const { finishMutation, requestKeyHeaders } = require('./operations')
7
+ const { parseSetFlags, readSettingsFile, mergePatches, checkPatch, formatSchema, formatSettings, formatChanges, PROTECTED_ENVS } = require('../settings')
8
+ const { readManifest, environmentSettings } = require('../release-manifest')
9
+ const { compareEnvironments, formatComparison } = require('../env-compare')
10
+
11
+ const USAGE = 'usage: saaslayer settings <schema|get|set|diff> … (see saaslayer --help)'
12
+
13
+ /**
14
+ * @param {object} flags
15
+ * @param {string} command for messages
16
+ */
17
+ function oneEnv(flags, command) {
18
+ if (Array.isArray(flags.env)) throw new Error(`${command} takes one --env`)
19
+ return flags
20
+ }
21
+
22
+ /**
23
+ * Resolve the deployment for (project, env, region), print its id under the scope line, and read its settings.
24
+ * @param {object} flags
25
+ * @returns {Promise<{ deployment: Awaited<ReturnType<typeof resolveDeployment>>, settings: import('../settings').DeploymentSettings }>}
26
+ */
27
+ async function readDeploymentSettings(flags) {
28
+ const deployment = await resolveDeployment(flags)
29
+ if (!flags.json) console.error(`deployment: ${deployment.deploymentId} (${deployment.region})`)
30
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, undefined, flags)
31
+ return { deployment, settings: doc.data.attributes }
32
+ }
33
+
34
+ /**
35
+ * @param {string} module
36
+ * @param {string} revision
37
+ * @param {object} flags
38
+ * @returns {Promise<import('../settings').SettingsSchema>}
39
+ */
40
+ async function fetchSchema(module, revision, flags) {
41
+ const doc = await apiCall('GET', `/api/modules/${encodeURIComponent(module)}/settings-schema?revision=${encodeURIComponent(revision)}`, undefined, flags)
42
+ return doc.data.attributes
43
+ }
44
+
45
+ /** `settings schema --module M [--revision SHA]`; without --revision, the revision the selected deployment runs. @param {object} flags */
46
+ async function settingsSchema(flags) {
47
+ const module = flags.module
48
+ if (typeof module !== 'string') throw new Error('settings schema requires --module <module id> (`saaslayer stacks` lists them)')
49
+ let revision = typeof flags.revision === 'string' ? flags.revision : null
50
+ if (!revision) {
51
+ const { deployment, settings } = await readDeploymentSettings(oneEnv(flags, 'settings schema'))
52
+ const deployed = settings.modules.find((m) => m.module === module)
53
+ if (!deployed || !deployed.revision) throw new Error(`${module} is not deployed in ${deployment.deploymentId} — pass --revision <commit sha>`)
54
+ revision = deployed.revision
55
+ }
56
+ const schema = await fetchSchema(module, revision, flags)
57
+ console.log(flags.json ? JSON.stringify(schema, null, 2) : formatSchema(schema).join('\n'))
58
+ return schema
59
+ }
60
+
61
+ /** `settings get --env E`. @param {object} flags */
62
+ async function settingsGet(flags) {
63
+ const { settings } = await readDeploymentSettings(oneEnv(flags, 'settings get'))
64
+ console.log(flags.json ? JSON.stringify(settings, null, 2) : formatSettings(settings).join('\n'))
65
+ return settings
66
+ }
67
+
68
+ /**
69
+ * Check a patch against the deployment's schemas and write it with the settings revision just read. Refusals happen
70
+ * before anything is sent. Waits for the operation unless --no-wait. Shared by `settings set` and `update --param`.
71
+ * @param {import('../settings').SettingsPatch} input
72
+ * @param {object} flags
73
+ */
74
+ async function applySettings(input, flags) {
75
+ const { deployment, settings } = await readDeploymentSettings(flags)
76
+ const schemas = Object.fromEntries(settings.modules.filter((m) => !m.schemaError).map((m) => [m.module, { module: m.module, revision: m.revision, settings: m.settings }]))
77
+ const { patch, billing } = checkPatch(input, schemas, { op: 'update' })
78
+ const reason = typeof flags.reason === 'string' ? flags.reason : undefined
79
+ if (!reason && billing.length) throw new Error(`${billing.join(', ')} changes billing: pass --reason <text>`)
80
+ if (!reason && PROTECTED_ENVS.has(deployment.env)) throw new Error(`${deployment.env} is a protected environment: pass --reason <text>`)
81
+ console.log(`Changing settings of ${deployment.deploymentId} (settings revision ${settings.settingsRevision}):`)
82
+ for (const line of formatChanges(patch, settings)) console.log(line)
83
+ const attributes = { expectedRevision: settings.settingsRevision, settings: patch, ...(reason ? { reason } : {}) }
84
+ let res
85
+ try {
86
+ res = await apiCall('PATCH', `/api/deployments/${encodeURIComponent(deployment.deploymentId)}/settings`, { data: { type: 'deployment-settings', attributes } }, flags, { headers: requestKeyHeaders() })
87
+ } catch (err) {
88
+ if (err.status === 409) err.message += `\nthe settings changed after they were read (revision ${settings.settingsRevision}): check them with \`saaslayer settings get\` and run the command again`
89
+ throw err
90
+ }
91
+ const written = res.data.attributes
92
+ console.log(`✅ settings revision ${settings.settingsRevision} → ${written.settingsRevision} (operation ${written.operationId})`)
93
+ return finishMutation({ response: res, deploymentId: deployment.deploymentId, flags })
94
+ }
95
+
96
+ /** `settings set --env E (--set M.S=V … | --file F) [--reason T]`. @param {object} flags */
97
+ async function settingsSet(flags) {
98
+ const patch = mergePatches(typeof flags.file === 'string' ? readSettingsFile(flags.file) : undefined, parseSetFlags(flags.set, '--set'))
99
+ if (!patch) throw new Error('settings set needs --set <module>.<Setting>=<value> or --file <settings.json>')
100
+ return applySettings(patch, oneEnv(flags, 'settings set'))
101
+ }
102
+
103
+ /**
104
+ * `settings diff --env A --env B [--manifest F]`: module revisions and settings that differ (create-only and secret
105
+ * marked), each side's settings revision, and the gaps between them; with a release manifest, each environment is also
106
+ * checked against the bundle, its permissions writer format and its settings in the manifest.
107
+ * @param {object} flags
108
+ */
109
+ async function settingsDiff(flags) {
110
+ const envs = Array.isArray(flags.env) ? flags.env : []
111
+ if (envs.length !== 2) throw new Error('settings diff needs two --env flags, e.g. --env staging --env prod')
112
+ if (envs[0] === envs[1]) throw new Error('settings diff compares two different environments')
113
+ const manifestFile = typeof flags.manifest === 'string' ? flags.manifest : null
114
+ const manifest = manifestFile ? readManifest(manifestFile) : null
115
+ const envPatches = manifest ? Object.fromEntries(envs.map((env) => [env, environmentSettings(manifest, /** @type {string} */ (manifestFile), env, undefined)])) : {}
116
+ const [a, b] = await Promise.all(envs.map((env) => readDeploymentSettings({ ...flags, env })))
117
+ const comparison = compareEnvironments({ env: envs[0], settings: a.settings }, { env: envs[1], settings: b.settings }, { manifest, envPatches })
118
+ if (flags.json) {
119
+ const side = (s) => ({ deploymentId: s.deployment.deploymentId, settingsRevision: s.settings.settingsRevision })
120
+ console.log(JSON.stringify({ [envs[0]]: side(a), [envs[1]]: side(b), bundleRevision: comparison.bundleRevision, modules: comparison.modules, differences: comparison.settings, gaps: comparison.gaps }, null, 2))
121
+ return comparison
122
+ }
123
+ console.log(`settings revision: ${envs[0]}=${a.settings.settingsRevision} (${a.deployment.deploymentId}) ${envs[1]}=${b.settings.settingsRevision} (${b.deployment.deploymentId})`)
124
+ for (const line of formatComparison(comparison)) console.log(line)
125
+ return comparison
126
+ }
127
+
128
+ /**
129
+ * @param {string|undefined} sub
130
+ * @param {object} flags
131
+ */
132
+ async function settingsCommand(sub, flags) {
133
+ if (sub === 'schema') return settingsSchema(flags)
134
+ if (sub === 'get') return settingsGet(flags)
135
+ if (sub === 'set') return settingsSet(flags)
136
+ if (sub === 'diff') return settingsDiff(flags)
137
+ throw new Error(USAGE)
138
+ }
139
+
140
+ module.exports = { settingsCommand, applySettings, fetchSchema, readDeploymentSettings }
@@ -1,16 +1,21 @@
1
- // `saaslayer stacks` (ctsc.5) — list the vendable stacks a project can deploy (from the BFF catalog).
1
+ // `saaslayer stacks` (ctsc.5) — list the modules a project can deploy (from the BFF catalog, GET /api/stacks):
2
+ // module id, display copy, regions, required modules and the stable outputs SDK discovery relies on.
2
3
  'use strict'
3
- const { apiCall } = require('../api-client')
4
+ const { fetchModuleCatalog } = require('../module-catalog')
4
5
 
5
6
  async function stacks(flags) {
6
- const res = await apiCall('GET', '/api/stacks', undefined, flags)
7
- const rows = res.data || []
8
- console.log('Deployable stacks:')
7
+ const rows = await fetchModuleCatalog(flags)
8
+ console.log('Deployable modules:')
9
9
  for (const r of rows) {
10
10
  const a = r.attributes || {}
11
- console.log(` ${a.service || r.id}${a.description ? ' — ' + a.description : ''}`)
11
+ console.log(` ${r.id}${a.displayName ? ` ${a.displayName}` : ''}${a.description ? ' — ' + a.description : ''}`)
12
+ console.log(` regions: ${a.supportedRegions ? a.supportedRegions.join(', ') : 'any'}`)
13
+ const deps = a.dependencies || []
14
+ if (deps.length) console.log(` requires: ${deps.map((d) => `${d.module} (${d.phase})`).join(', ')}`)
15
+ const stable = (a.outputs || []).filter((o) => o.stability === 'stable').map((o) => o.name)
16
+ if (stable.length) console.log(` outputs: ${stable.join(', ')}`)
12
17
  }
13
- console.log('\nDeploy with: saaslayer deploy --services <a,b>')
18
+ console.log('\nDeploy with: saaslayer deploy --services <module-id,…> [--set <module-id>.<Setting>=<value>]')
14
19
  return rows
15
20
  }
16
21