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
@@ -1,36 +1,10 @@
1
- // Customer IAM principals for a cloud-prem SaaSLayer deployment: the SSM path that declares them, a light file check,
2
- // and the exchange of a signed STS GetCallerIdentity proof (your AWS credentials) for an rbac iam_ token.
1
+ // Customer IAM principals for a cloud-prem SaaSLayer deployment: your AWS credentials and the exchange of a signed STS
2
+ // GetCallerIdentity proof (proving a declared role) for a permissions iam_ token.
3
3
  'use strict'
4
4
  const crypto = require('crypto')
5
5
  const { execFileSync } = require('child_process')
6
6
  const { signRequest } = require('./aws-sigv4')
7
7
 
8
- /**
9
- * SSM parameter (in the customer's own account) holding the deployment's IAM principals.
10
- * @param {string} deploymentId
11
- * @param {string} [serviceInstance] rbac service instance ('_' = default)
12
- */
13
- function iamPrincipalsParam(deploymentId, serviceInstance = '_') {
14
- if (!deploymentId) throw new Error('a deployment id is required')
15
- return `/saaslayer/deployment/${deploymentId}/${serviceInstance}/rbac/iam-principals`
16
- }
17
-
18
- /**
19
- * Shape check before writing; rbac-service does the full validation and ignores an invalid config.
20
- * @param {{ principals?: Array<{ principalId?: string, roleArn?: string, scopes?: string[] }> }} file
21
- * @returns {string[]}
22
- */
23
- function validatePrincipalsFile(file) {
24
- if (!file || !Array.isArray(file.principals)) return ['file must be { "principals": [...] }']
25
- const errors = []
26
- file.principals.forEach((p, i) => {
27
- if (!p.principalId) errors.push(`principals[${i}]: principalId is required`)
28
- if (!/^arn:aws[a-z-]*:iam::\d{12}:(role|user)\//.test(p.roleArn || '')) errors.push(`principals[${i}]: roleArn must be an IAM role or user ARN`)
29
- if (!Array.isArray(p.scopes) || !p.scopes.length) errors.push(`principals[${i}]: at least one scope is required`)
30
- })
31
- return errors
32
- }
33
-
34
8
  /**
35
9
  * Your current AWS credentials (env, profile, SSO) via the AWS CLI.
36
10
  * @param {{ profile?: string }} [opts]
@@ -71,7 +45,7 @@ function buildStsEnvelope({ principalId, region, credentials, now = new Date(),
71
45
  }
72
46
 
73
47
  /**
74
- * Exchange your AWS identity for an iam_ token on the deployment's rbac API.
48
+ * Exchange your AWS identity for an iam_ token on the deployment's permissions API.
75
49
  * @param {{ apiBase: string, principalId: string, region: string, credentials?: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, profile?: string }} opts
76
50
  * @returns {Promise<string>}
77
51
  */
@@ -90,4 +64,4 @@ async function exchangeIamToken({ apiBase, principalId, region, credentials, pro
90
64
  return body.data.attributes.token
91
65
  }
92
66
 
93
- module.exports = { iamPrincipalsParam, validatePrincipalsFile, awsCredentials, buildStsEnvelope, exchangeIamToken }
67
+ module.exports = { awsCredentials, buildStsEnvelope, exchangeIamToken }
@@ -0,0 +1,66 @@
1
+ // The public module catalog (GET /api/stacks) and the checks deploy/update run against it before sending a request:
2
+ // module ids, required dependencies, and the module keys of --param flags.
3
+ 'use strict'
4
+ const { apiCall } = require('./api-client')
5
+
6
+ /**
7
+ * @typedef {{ id: string, attributes: { dependencies?: Array<{ module: string, phase: string }> } & Record<string, unknown> }} CatalogModule
8
+ */
9
+
10
+ /**
11
+ * @param {object} flags
12
+ * @returns {Promise<CatalogModule[]>}
13
+ */
14
+ async function fetchModuleCatalog(flags) {
15
+ const res = await apiCall('GET', '/api/stacks', undefined, flags)
16
+ return res.data || []
17
+ }
18
+
19
+ /**
20
+ * The refusal for a name that is not a module id, suggesting ids that share its first word (permissions → permissions-service).
21
+ * @param {string} name
22
+ * @param {CatalogModule[]} modules
23
+ * @returns {string}
24
+ */
25
+ function unknownModuleMessage(name, modules) {
26
+ const word = name.split('-')[0]
27
+ const similar = modules.map((m) => m.id).filter((id) => id.split('-')[0] === word)
28
+ const hint = similar.length ? ` — did you mean ${similar.join(' or ')}?` : ' —'
29
+ return `unknown module "${name}"${hint} \`saaslayer stacks\` lists the module ids`
30
+ }
31
+
32
+ /**
33
+ * @param {string[]} ids
34
+ * @param {CatalogModule[]} modules
35
+ */
36
+ function checkModuleIds(ids, modules) {
37
+ for (const id of ids) {
38
+ if (!modules.some((m) => m.id === id)) throw new Error(unknownModuleMessage(id, modules))
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Every selected module's dependencies must be selected too.
44
+ * @param {string[]} ids
45
+ * @param {CatalogModule[]} modules
46
+ */
47
+ function checkDependencies(ids, modules) {
48
+ for (const id of ids) {
49
+ const m = modules.find((x) => x.id === id)
50
+ for (const dep of (m && m.attributes.dependencies) || []) {
51
+ if (!ids.includes(dep.module)) throw new Error(`${id} needs ${dep.module} in the same deployment (${dep.phase}) — add it to --services`)
52
+ }
53
+ }
54
+ }
55
+
56
+ /**
57
+ * @param {Record<string, Record<string, string>>} parameters service-keyed --param values
58
+ * @param {CatalogModule[]} modules
59
+ */
60
+ function checkParamModules(parameters, modules) {
61
+ for (const [id, values] of Object.entries(parameters)) {
62
+ if (!modules.some((m) => m.id === id)) throw new Error(`--param ${id}.${Object.keys(values)[0]}: ${unknownModuleMessage(id, modules)}`)
63
+ }
64
+ }
65
+
66
+ module.exports = { fetchModuleCatalog, checkModuleIds, checkDependencies, checkParamModules }
@@ -0,0 +1,43 @@
1
+ // One call to a deployment's permissions API from a CLI command: resolves --api-base (or $SAASLAYER_API_BASE), the selected auth
2
+ // (deployment login, API key or IAM), and throws with the API's error codes and messages.
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, deployment?: string, as?: string }} PermissionsFlags
9
+ * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
10
+ */
11
+
12
+ /**
13
+ * The permissions API base.
14
+ * @param {string} label @param {PermissionsFlags} flags
15
+ */
16
+ function apiBaseOf(label, flags) {
17
+ const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
18
+ if (!apiBase) throw new Error(`${label}: --api-base (or $SAASLAYER_API_BASE) is required`)
19
+ return apiBase.replace(/\/$/, '')
20
+ }
21
+
22
+ /**
23
+ * Call a permissions route; throws with the API's codes and messages.
24
+ * @param {string} label @param {PermissionsFlags} flags @param {Deps} deps @param {string} method @param {string} path @param {object} [body]
25
+ * @returns {Promise<any>} the response document
26
+ */
27
+ async function permissionsRequest(label, flags, deps, method, path, body) {
28
+ const apiBase = apiBaseOf(label, flags)
29
+ const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
30
+ const res = await fetch(`${apiBase}${path}`, {
31
+ method,
32
+ headers: body ? { ...auth, 'content-type': 'application/json' } : auth,
33
+ ...(body ? { body: JSON.stringify(body) } : {}),
34
+ })
35
+ const json = await res.json().catch(() => ({}))
36
+ if (!res.ok) {
37
+ const detail = ((json && json.errors) || []).map((/** @type {{ code?: string, message?: string, detail?: string }} */ e) => [e.code, e.message || e.detail].filter(Boolean).join(': ')).join('; ') || JSON.stringify(json)
38
+ throw new Error(`${label} failed (${res.status}${detail ? ` ${detail}` : ''})`)
39
+ }
40
+ return json
41
+ }
42
+
43
+ module.exports = { permissionsRequest }
@@ -0,0 +1,334 @@
1
+ // Release manifest: the format (one tested bundle revision with each module's settings-contract hash, CLI/SDK versions,
2
+ // the permissions compatibility declaration, per-environment settings references) and the preflight `update --manifest` runs.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const fs = require('fs')
6
+ const path = require('path')
7
+ const { PROTECTED_ENVS, readSettingsFile, checkPatch, valueProblem } = require('./settings')
8
+
9
+ const MANIFEST_SCHEMA_VERSION = 1
10
+ // The module whose service writes the permission docs direct-mode readers parse, and the setting that picks the format.
11
+ const PERMISSIONS_WRITER = Object.freeze({ module: 'permissions-service', permissionDocSetting: 'PermissionDocV2' })
12
+
13
+ const COMMIT_SHA = /^[0-9a-f]{40}$/
14
+ const SHA256 = /^[0-9a-f]{64}$/
15
+ const EXACT_VERSION = /^\d+\.\d+\.\d+$/
16
+ const ENV_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/
17
+ const MODULE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/
18
+
19
+ // The engine-core direct-mode contract: monorepo source first (vendor/ is a prepack snapshot), else the published copy.
20
+ const MONOREPO_DIRECT_MODE = path.join(__dirname, '../../permissions-engine-core/src/direct-mode-contract.js')
21
+ const VENDORED_DIRECT_MODE = path.join(__dirname, '../vendor/permissions-engine-core/direct-mode-contract.js')
22
+
23
+ /** @returns {typeof import('../../permissions-engine-core/src/direct-mode-contract.js')} */
24
+ function directModeContract() {
25
+ return require(fs.existsSync(MONOREPO_DIRECT_MODE) ? MONOREPO_DIRECT_MODE : VENDORED_DIRECT_MODE)
26
+ }
27
+
28
+ /**
29
+ * @typedef {{ decisionEngineContract: number, writes: { permissionDoc: number, registrySnapshot: number } }} WriterRelease
30
+ * @typedef {{ settings: string, settingsSha256?: string }} EnvironmentRef
31
+ * @typedef {{ schemaVersion: 1, name?: string,
32
+ * bundle: { revision: string, modules: Record<string, { settingsContractSha256: string }> },
33
+ * tooling: { cli: string, sdks?: Record<string, string> },
34
+ * compatibility?: { permissions?: WriterRelease },
35
+ * permissionsDirectMode?: { readers: unknown },
36
+ * environments?: Record<string, EnvironmentRef> }} ReleaseManifest
37
+ * @typedef {{ check: string, code: string, message: string, action?: string }} Problem
38
+ */
39
+
40
+ /** @param {unknown} v @returns {v is Record<string, any>} */
41
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
42
+ /** @param {unknown} v */
43
+ const isPositiveInt = (v) => Number.isInteger(v) && /** @type {number} */ (v) >= 1
44
+
45
+ /**
46
+ * Refuse any field outside `allowed` (so secrets, users, role assignments or accounts never ride along). Messages name
47
+ * the field, never its value.
48
+ * @param {Record<string, unknown>} obj @param {string[]} allowed @param {string} at @param {string[]} problems
49
+ */
50
+ function onlyFields(obj, allowed, at, problems) {
51
+ for (const key of Object.keys(obj)) if (!allowed.includes(key)) problems.push(`${at}${key}: not a release manifest field`)
52
+ }
53
+
54
+ /**
55
+ * Check a parsed manifest document. Every problem is reported, not just the first.
56
+ * @param {unknown} doc
57
+ * @returns {{ manifest: ReleaseManifest|null, problems: string[] }}
58
+ */
59
+ function validateManifest(doc) {
60
+ /** @type {string[]} */
61
+ const problems = []
62
+ if (!isObject(doc)) return { manifest: null, problems: ['a release manifest is a JSON object'] }
63
+ onlyFields(doc, ['schemaVersion', 'name', 'bundle', 'tooling', 'compatibility', 'permissionsDirectMode', 'environments'], '', problems)
64
+ if (doc.schemaVersion !== MANIFEST_SCHEMA_VERSION) problems.push(`schemaVersion must be ${MANIFEST_SCHEMA_VERSION}`)
65
+ if (doc.name !== undefined && (typeof doc.name !== 'string' || !doc.name)) problems.push('name must be a non-empty string')
66
+
67
+ const bundle = doc.bundle
68
+ if (!isObject(bundle)) problems.push('bundle is required: { revision, modules }')
69
+ else {
70
+ onlyFields(bundle, ['revision', 'modules'], 'bundle.', problems)
71
+ if (typeof bundle.revision !== 'string' || !COMMIT_SHA.test(bundle.revision)) problems.push('bundle.revision must be a full 40-character commit sha')
72
+ if (!isObject(bundle.modules) || !Object.keys(bundle.modules).length) problems.push('bundle.modules must name at least one module')
73
+ else {
74
+ for (const [id, entry] of Object.entries(bundle.modules)) {
75
+ const at = `bundle.modules.${id}`
76
+ if (!MODULE_ID.test(id)) { problems.push(`${at}: not a module id`); continue }
77
+ if (!isObject(entry)) { problems.push(`${at} must be { settingsContractSha256 }`); continue }
78
+ onlyFields(entry, ['settingsContractSha256'], `${at}.`, problems)
79
+ if (typeof entry.settingsContractSha256 !== 'string' || !SHA256.test(entry.settingsContractSha256)) problems.push(`${at}.settingsContractSha256 must be a sha256 (64 lowercase hex)`)
80
+ }
81
+ }
82
+ }
83
+
84
+ const tooling = doc.tooling
85
+ if (!isObject(tooling)) problems.push('tooling is required: { cli, sdks? }')
86
+ else {
87
+ onlyFields(tooling, ['cli', 'sdks'], 'tooling.', problems)
88
+ if (typeof tooling.cli !== 'string' || !EXACT_VERSION.test(tooling.cli)) problems.push('tooling.cli must be an exact x.y.z version')
89
+ if (tooling.sdks !== undefined) {
90
+ if (!isObject(tooling.sdks)) problems.push('tooling.sdks must be { "<package>": "x.y.z" }')
91
+ else for (const [pkg, v] of Object.entries(tooling.sdks)) if (typeof v !== 'string' || !EXACT_VERSION.test(v)) problems.push(`tooling.sdks.${pkg} must be an exact x.y.z version`)
92
+ }
93
+ }
94
+
95
+ const compatibility = doc.compatibility
96
+ if (compatibility !== undefined) {
97
+ if (!isObject(compatibility)) problems.push('compatibility must be { permissions? }')
98
+ else {
99
+ onlyFields(compatibility, ['permissions'], 'compatibility.', problems)
100
+ const writer = compatibility.permissions
101
+ if (writer !== undefined) {
102
+ const valid = isObject(writer) && isPositiveInt(writer.decisionEngineContract) && isObject(writer.writes)
103
+ && isPositiveInt(writer.writes.permissionDoc) && isPositiveInt(writer.writes.registrySnapshot)
104
+ if (!valid) problems.push('compatibility.permissions must be { decisionEngineContract, writes: { permissionDoc, registrySnapshot } } (positive integers)')
105
+ else {
106
+ onlyFields(writer, ['decisionEngineContract', 'writes'], 'compatibility.permissions.', problems)
107
+ onlyFields(writer.writes, ['permissionDoc', 'registrySnapshot'], 'compatibility.permissions.writes.', problems)
108
+ }
109
+ }
110
+ }
111
+ }
112
+ const hasWriter = isObject(bundle) && isObject(bundle.modules) && PERMISSIONS_WRITER.module in bundle.modules
113
+ if (hasWriter && !(isObject(compatibility) && compatibility.permissions !== undefined)) {
114
+ problems.push(`compatibility.permissions is required when the bundle has ${PERMISSIONS_WRITER.module}: what the tested release writes (saaslayer release-manifest create records it)`)
115
+ }
116
+
117
+ // Reader entries are checked by the preflight (declaration_invalid), so a bad entry is reported with its upgrade action.
118
+ if (doc.permissionsDirectMode !== undefined) {
119
+ if (!isObject(doc.permissionsDirectMode)) problems.push('permissionsDirectMode must be { readers: [...] }')
120
+ else onlyFields(doc.permissionsDirectMode, ['readers'], 'permissionsDirectMode.', problems)
121
+ }
122
+
123
+ if (doc.environments !== undefined) {
124
+ if (!isObject(doc.environments)) problems.push('environments must be { "<env>": { settings, settingsSha256? } }')
125
+ else {
126
+ for (const [env, ref] of Object.entries(doc.environments)) {
127
+ const at = `environments.${env}`
128
+ if (!ENV_NAME.test(env)) { problems.push(`${at}: not an environment name (lowercase letters, digits, '-')`); continue }
129
+ if (!isObject(ref)) { problems.push(`${at} must be { settings, settingsSha256? }`); continue }
130
+ onlyFields(ref, ['settings', 'settingsSha256'], `${at}.`, problems)
131
+ if (typeof ref.settings !== 'string' || !ref.settings) problems.push(`${at}.settings must be a settings file path (relative to the manifest)`)
132
+ if (ref.settingsSha256 !== undefined && (typeof ref.settingsSha256 !== 'string' || !SHA256.test(ref.settingsSha256))) problems.push(`${at}.settingsSha256 must be a sha256 (64 lowercase hex)`)
133
+ }
134
+ }
135
+ }
136
+ return { manifest: problems.length ? null : /** @type {ReleaseManifest} */ (doc), problems }
137
+ }
138
+
139
+ /**
140
+ * Read and check a manifest file.
141
+ * @param {string} file
142
+ * @returns {ReleaseManifest}
143
+ */
144
+ function readManifest(file) {
145
+ let doc
146
+ try {
147
+ doc = JSON.parse(fs.readFileSync(file, 'utf8'))
148
+ } catch (err) {
149
+ throw new Error(`release manifest ${file}: ${err.code === 'ENOENT' ? 'file not found' : 'not valid JSON'}`)
150
+ }
151
+ const { manifest, problems } = validateManifest(doc)
152
+ if (!manifest) throw new Error(`release manifest ${file} is invalid:\n${problems.map((p) => ` - ${p}`).join('\n')}`)
153
+ return manifest
154
+ }
155
+
156
+ /**
157
+ * The settings patch for one environment: the manifest's reference (relative to the manifest, checked against its
158
+ * sha256 when given) or a --settings file. Undefined when neither names settings.
159
+ * @param {ReleaseManifest} manifest
160
+ * @param {string} manifestFile
161
+ * @param {string} env
162
+ * @param {unknown} settingsFlag --settings
163
+ * @returns {import('./settings').SettingsPatch|undefined}
164
+ */
165
+ function environmentSettings(manifest, manifestFile, env, settingsFlag) {
166
+ const ref = (manifest.environments || {})[env]
167
+ if (ref && settingsFlag !== undefined) throw new Error(`the manifest already names the ${env} settings (${ref.settings}); drop --settings`)
168
+ if (!ref) return typeof settingsFlag === 'string' ? readSettingsFile(settingsFlag) : undefined
169
+ const file = path.resolve(path.dirname(manifestFile), ref.settings)
170
+ if (ref.settingsSha256) {
171
+ let bytes
172
+ try { bytes = fs.readFileSync(file) } catch { throw new Error(`${ref.settings}: file not found (environments.${env}.settings)`) }
173
+ if (crypto.createHash('sha256').update(bytes).digest('hex') !== ref.settingsSha256) throw new Error(`${ref.settings} does not match environments.${env}.settingsSha256`)
174
+ }
175
+ return readSettingsFile(file)
176
+ }
177
+
178
+ /** Key-sorted JSON, byte-identical to the deployer's canonicalJson (the hash input at publish). @param {unknown} value @returns {string} */
179
+ function canonicalJson(value) {
180
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
181
+ if (value && typeof value === 'object') return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(/** @type {any} */ (value)[k])}`).join(',')}}`
182
+ return JSON.stringify(value) ?? 'null'
183
+ }
184
+
185
+ /** The integrity hash of a settings contract artifact, as published. @param {unknown} contract */
186
+ const contractHash = (contract) => crypto.createHash('sha256').update(canonicalJson(contract)).digest('hex')
187
+
188
+ /** @param {string} sha */
189
+ const short = (sha) => (sha ? sha.slice(0, 7) : '—')
190
+
191
+ /**
192
+ * The permission-doc format an environment writes, from its effective PermissionDocV2 value.
193
+ * @param {unknown} value
194
+ */
195
+ const permissionDocFormatFor = (value) => (String(value) === 'true' ? 2 : 1)
196
+
197
+ /**
198
+ * What a permissions-service deployment at this engine contract writes, given its PermissionDocV2 value.
199
+ * @param {unknown} permissionDocV2
200
+ * @returns {WriterRelease}
201
+ */
202
+ function permissionsWriterRelease(permissionDocV2) {
203
+ const { DECISION_ENGINE_CONTRACT, READABLE_FORMATS } = directModeContract()
204
+ return { decisionEngineContract: DECISION_ENGINE_CONTRACT, writes: { permissionDoc: permissionDocFormatFor(permissionDocV2), registrySnapshot: Math.max(...READABLE_FORMATS.registrySnapshot) } }
205
+ }
206
+
207
+ /**
208
+ * @typedef {{ manifest: ReleaseManifest, env: string, current: import('./settings').DeploymentSettings,
209
+ * targetSchemas: Record<string, { schema?: import('./settings').SettingsSchema, error?: string }>,
210
+ * envPatch: import('./settings').SettingsPatch|undefined, reason: string|undefined, cliVersion: string, noWait: boolean }} PreflightInput
211
+ */
212
+
213
+ /**
214
+ * Preflight a manifest against one deployment, before anything is sent: tooling, bundle modules and contract
215
+ * integrity, schema transitions from each module's deployed revision to the bundle revision, the environment's
216
+ * settings against the target contracts, direct-mode readers against what the release writes, and the reason a
217
+ * protected environment needs. Messages name settings, never their values.
218
+ * @param {PreflightInput} input
219
+ * @returns {{ ok: boolean, problems: Problem[], moveRelease: boolean, patch: import('./settings').SettingsPatch|null, fromRevisions: string[] }}
220
+ */
221
+ function preflightManifest({ manifest, env, current, targetSchemas, envPatch, reason, cliVersion, noWait }) {
222
+ /** @type {Problem[]} */
223
+ const problems = []
224
+ const add = (check, code, message, action) => problems.push({ check, code, message, ...(action ? { action } : {}) })
225
+ const target = manifest.bundle.revision
226
+
227
+ if (cliVersion !== manifest.tooling.cli) {
228
+ add('tooling', 'cli_version', `this CLI is ${cliVersion}; the release was tested with ${manifest.tooling.cli}`, `run the tested CLI: npx saaslayer@${manifest.tooling.cli} update --manifest …`)
229
+ }
230
+ if (current.pending) add('deployment', 'operation_pending', `operation ${current.pending.operationId} is still running on ${current.deploymentId}`, `wait for it: saaslayer operations watch ${current.pending.operationId} --deployment ${current.deploymentId}`)
231
+
232
+ const deployed = new Map(current.modules.map((m) => [m.module, m]))
233
+ for (const m of current.modules) {
234
+ if (!(m.module in manifest.bundle.modules)) add('bundle', 'module_not_in_bundle', `${m.module} is deployed in ${env} but not in the release bundle; the update moves every module to ${short(target)}`, `add ${m.module} to the bundle (tested) or remove it from ${env}`)
235
+ }
236
+ /** @type {Record<string, import('./settings').SettingsSchema>} */
237
+ const schemas = {}
238
+ for (const [module, { settingsContractSha256 }] of Object.entries(manifest.bundle.modules)) {
239
+ if (!deployed.has(module)) add('bundle', 'module_not_deployed', `${module} is in the release bundle but not deployed in ${env}`, `add it first: saaslayer service add ${module} --env ${env}`)
240
+ const got = targetSchemas[module] || { error: 'NOT_FETCHED' }
241
+ if (!got.schema) { add('contracts', 'contract_missing', `${module} has no published settings contract at ${short(target)} (${got.error})`); continue }
242
+ if (contractHash(got.schema) !== settingsContractSha256) {
243
+ add('contracts', 'contract_hash_mismatch', `${module}@${short(target)}: the published settings contract is not the one the release was tested with (sha256 differs)`)
244
+ }
245
+ schemas[module] = got.schema
246
+ }
247
+
248
+ // Schema transitions: what each deployed module carries must stay meaningful at the target revision.
249
+ for (const m of current.modules) {
250
+ const to = schemas[m.module]
251
+ if (!to) continue
252
+ const byName = new Map(to.settings.map((s) => [s.name, s]))
253
+ for (const s of m.settings) {
254
+ const label = `${m.module}.${s.name}`
255
+ const t = byName.get(s.name)
256
+ if (!t) {
257
+ if (s.source === 'set') add('transitions', 'setting_removed', `${label} is set in ${env} but the target revision ${short(target)} does not declare it`, `reset it to its default first (null in a settings file: saaslayer settings set --env ${env} --file …)`)
258
+ continue
259
+ }
260
+ if (s.source === 'set' && Boolean(s.secret) !== Boolean(t.secret)) {
261
+ add('transitions', 'secret_changed', `${label} is set in ${env} and ${t.secret ? 'becomes' : 'stops being'} secret at the target revision`, 'set it again after the release moves')
262
+ } else if (s.source === 'set' && !s.secret) {
263
+ const problem = valueProblem(t, s.value)
264
+ if (problem) add('transitions', 'value_invalid', `${label}: the value set in ${env} is not valid at the target revision (must be ${problem})`, `change it first to a value both revisions accept: saaslayer settings set --env ${env} --set ${label}=…`)
265
+ }
266
+ if (t.updateBehavior === 'create-only' && s.source === 'default' && canonicalJson(s.default) !== canonicalJson(t.default)) {
267
+ add('transitions', 'create_only_default_changed', `${label} is create-only and its default changes at the target revision; the standing deployment would get a different value`, 'this release cannot move onto a standing deployment without a documented migration')
268
+ }
269
+ }
270
+ }
271
+
272
+ // The environment's settings, minus values the deployment already has (a secret reference is always sent).
273
+ /** @type {import('./settings').SettingsPatch|null} */
274
+ let patch = null
275
+ let billing = []
276
+ if (envPatch) {
277
+ /** @type {import('./settings').SettingsPatch} */
278
+ const reduced = {}
279
+ for (const [module, values] of Object.entries(envPatch)) {
280
+ const mod = deployed.get(module)
281
+ for (const [name, value] of Object.entries(values)) {
282
+ const s = mod && mod.settings.find((x) => x.name === name)
283
+ const unchanged = s && !s.secret && (value === null ? s.source !== 'set' : s.value !== null && String(s.value) === String(value))
284
+ if (!unchanged) reduced[module] = { ...(reduced[module] || {}), [name]: value }
285
+ }
286
+ }
287
+ try {
288
+ billing = checkPatch(reduced, schemas, { op: 'update' }).billing
289
+ patch = reduced
290
+ } catch (err) {
291
+ add('settings', 'settings_invalid', err.message)
292
+ }
293
+ }
294
+ const patchSize = patch ? Object.values(patch).reduce((n, v) => n + Object.keys(v).length, 0) : 0
295
+
296
+ // Direct-mode readers must read what the release writes, and the environment must write what the manifest declares.
297
+ if (PERMISSIONS_WRITER.module in manifest.bundle.modules && manifest.compatibility && manifest.compatibility.permissions) {
298
+ const release = manifest.compatibility.permissions
299
+ const pre = directModeContract().preflightDirectReaders(release, manifest.permissionsDirectMode)
300
+ if (!pre.ok) add('readers', 'direct_readers', `direct-mode readers: ${pre.outcome}${pre.readers.length ? ` (${pre.readers.filter((r) => !r.ok).map((r) => `${r.name}@${r.version} ${r.problem}`).join(', ')})` : ''}`, pre.actions.join('; '))
301
+ const writer = deployed.get(PERMISSIONS_WRITER.module)
302
+ const name = PERMISSIONS_WRITER.permissionDocSetting
303
+ const declared = writer && writer.settings.find((s) => s.name === name)
304
+ if (declared && schemas[PERMISSIONS_WRITER.module] && schemas[PERMISSIONS_WRITER.module].settings.some((s) => s.name === name)) {
305
+ const requested = envPatch && envPatch[PERMISSIONS_WRITER.module] && name in envPatch[PERMISSIONS_WRITER.module] ? envPatch[PERMISSIONS_WRITER.module][name] : declared.value
306
+ const writes = permissionDocFormatFor(requested)
307
+ if (writes !== release.writes.permissionDoc) {
308
+ add('readers', 'writer_format_mismatch', `${env} writes permissionDoc ${writes} (${PERMISSIONS_WRITER.module}.${name}) but the manifest declares permissionDoc ${release.writes.permissionDoc}`, `set ${PERMISSIONS_WRITER.module}.${name} for ${env} to match the tested release, or re-create the manifest`)
309
+ }
310
+ }
311
+ }
312
+
313
+ if (!reason && PROTECTED_ENVS.has(env)) add('reason', 'reason_required', `${env} is a protected environment: pass --reason <text>`)
314
+ else if (!reason && billing.length) add('reason', 'reason_required', `${billing.join(', ')} changes billing: pass --reason <text>`)
315
+
316
+ const fromRevisions = [...new Set(current.modules.map((m) => m.revision || '—'))]
317
+ const moveRelease = current.modules.some((m) => m.revision !== target)
318
+ if (noWait && moveRelease && patchSize) add('apply', 'no_wait_with_settings', 'the settings are written after the release move finishes, so --no-wait cannot be used with settings', 'drop --no-wait')
319
+ return { ok: problems.length === 0, problems, moveRelease, patch: patchSize ? patch : null, fromRevisions }
320
+ }
321
+
322
+ module.exports = {
323
+ MANIFEST_SCHEMA_VERSION,
324
+ PERMISSIONS_WRITER,
325
+ validateManifest,
326
+ readManifest,
327
+ environmentSettings,
328
+ canonicalJson,
329
+ contractHash,
330
+ permissionDocFormatFor,
331
+ short,
332
+ permissionsWriterRelease,
333
+ preflightManifest,
334
+ }
package/src/scope.js ADDED
@@ -0,0 +1,114 @@
1
+ // The scope a command acts on (org, project, deploy env) with where each value came from, the `scope:` line every
2
+ // scoped command prints, and the empty-result hint that lists the caller's projects that do have deployments.
3
+ 'use strict'
4
+ const context = require('./context-store')
5
+ const { apiCall } = require('./api-client')
6
+
7
+ /**
8
+ * @typedef {{ value: string|null, source: 'flag'|'context'|'default'|null }} ScopeValue
9
+ * @typedef {{ org: ScopeValue, project: ScopeValue & { kind: string }, env: ScopeValue }} Scope
10
+ */
11
+
12
+ /**
13
+ * A project is an RBAC tenant (tnt_ TypeID) and its id is the deployer customerId. Deployments created before
14
+ * projects existed carry a bare customer id. Both select the same deployments; the label says which one was given.
15
+ * @param {string} id
16
+ * @returns {'project id'|'customer id'}
17
+ */
18
+ function projectIdKind(id) {
19
+ return /^tnt_/.test(String(id)) ? 'project id' : 'customer id'
20
+ }
21
+
22
+ /**
23
+ * @param {unknown} flagValue
24
+ * @param {string} contextKey
25
+ * @returns {ScopeValue}
26
+ */
27
+ function fromFlagOrContext(flagValue, contextKey) {
28
+ if (typeof flagValue === 'string' && flagValue) return { value: flagValue, source: 'flag' }
29
+ const stored = context.get(contextKey)
30
+ return stored ? { value: stored, source: 'context' } : { value: null, source: null }
31
+ }
32
+
33
+ /**
34
+ * Resolve the org, project and deploy env for a scoped command. Throws when no project is selected.
35
+ * @param {object} flags
36
+ * @param {{ env: string }} defaults the env used when --env is absent ('all' for commands that span every env)
37
+ * @returns {Scope}
38
+ */
39
+ function resolveScope(flags, defaults) {
40
+ const project = fromFlagOrContext(flags.project, 'project')
41
+ if (!project.value) throw new Error('no project selected — run `saaslayer project use <id>` or pass --project')
42
+ return {
43
+ org: fromFlagOrContext(flags.org, 'org'),
44
+ project: { ...project, kind: projectIdKind(project.value) },
45
+ env: typeof flags.env === 'string' && flags.env ? { value: flags.env, source: 'flag' } : { value: defaults.env, source: 'default' },
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @param {Scope} scope
51
+ * @returns {string}
52
+ */
53
+ function formatScopeLine(scope) {
54
+ const sources = ['org', 'project', 'env'].filter((k) => scope[k].source).map((k) => `${k}=${scope[k].source}`)
55
+ return `scope: org=${scope.org.value || '—'} project=${scope.project.value} (${scope.project.kind}) env=${scope.env.value} (from: ${sources.join(' ')})`
56
+ }
57
+
58
+ /**
59
+ * Print the scope line on stderr so stdout stays the command's result. --json suppresses it.
60
+ * @param {Scope} scope
61
+ * @param {object} flags
62
+ */
63
+ function printScope(scope, flags) {
64
+ if (flags.json) return
65
+ console.error(formatScopeLine(scope))
66
+ }
67
+
68
+ /**
69
+ * Group the caller's live deployments by project/customer id.
70
+ * @param {Array<{ id: string, attributes?: Record<string, any> }>} rows GET /api/deployments data
71
+ * @returns {Array<{ id: string, orgId: string|null, count: number, environments: string[] }>}
72
+ */
73
+ function deployedProjects(rows) {
74
+ /** @type {Map<string, { id: string, orgId: string|null, count: number, environments: string[] }>} */
75
+ const byId = new Map()
76
+ for (const row of rows) {
77
+ const a = row.attributes || {}
78
+ if (!a.customerId || a.status === 'DESTROYED') continue
79
+ const entry = byId.get(a.customerId) || { id: a.customerId, orgId: a.orgId || null, count: 0, environments: [] }
80
+ entry.count++
81
+ if (a.environment && !entry.environments.includes(a.environment)) entry.environments.push(a.environment)
82
+ byId.set(a.customerId, entry)
83
+ }
84
+ return [...byId.values()]
85
+ }
86
+
87
+ /**
88
+ * Hint lines listing the projects with deployments, other than the one that came back empty.
89
+ * @param {ReturnType<typeof deployedProjects>} projects
90
+ * @param {string} emptyProjectId
91
+ * @returns {string[]}
92
+ */
93
+ function formatDeployedProjects(projects, emptyProjectId) {
94
+ const others = projects.filter((p) => p.id !== emptyProjectId)
95
+ if (!others.length) return ['you have no deployments in any project you can see — deploy with `saaslayer deploy`']
96
+ return [
97
+ 'projects you can see that have deployments:',
98
+ ...others.map((p) => ` ${p.id} (${projectIdKind(p.id)}) org ${p.orgId || '—'} ${p.count} deployment(s): ${p.environments.join(', ')}`),
99
+ 'retry with: saaslayer status --project <id> (or select it: saaslayer project use <id>)',
100
+ ]
101
+ }
102
+
103
+ /**
104
+ * Fetch the caller's deployments and build the empty-result hint.
105
+ * @param {Scope} scope
106
+ * @param {object} flags
107
+ * @returns {Promise<string[]>}
108
+ */
109
+ async function deployedProjectsHint(scope, flags) {
110
+ const doc = await apiCall('GET', '/api/deployments', undefined, flags)
111
+ return formatDeployedProjects(deployedProjects(doc.data || []), scope.project.value)
112
+ }
113
+
114
+ module.exports = { projectIdKind, resolveScope, formatScopeLine, printScope, deployedProjects, formatDeployedProjects, deployedProjectsHint }