saaslayer 0.0.2 → 0.1.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 (51) hide show
  1. package/README.md +195 -8
  2. package/bin/saaslayer.js +454 -38
  3. package/package.json +19 -4
  4. package/src/api-client.js +91 -0
  5. package/src/aws-sigv4.js +47 -0
  6. package/src/commands/access-admins.js +73 -0
  7. package/src/commands/accounts.js +54 -0
  8. package/src/commands/activity.js +33 -0
  9. package/src/commands/aws.js +132 -0
  10. package/src/commands/catalog.js +246 -0
  11. package/src/commands/context.js +64 -0
  12. package/src/commands/deploy.js +118 -0
  13. package/src/commands/first-admin.js +42 -0
  14. package/src/commands/foundation.js +405 -0
  15. package/src/commands/lifecycle.js +124 -0
  16. package/src/commands/login.js +261 -0
  17. package/src/commands/machine-trust.js +96 -0
  18. package/src/commands/migrate.js +290 -0
  19. package/src/commands/operations.js +140 -0
  20. package/src/commands/orgs.js +81 -0
  21. package/src/commands/permissions-inspect.js +228 -0
  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 +22 -0
  26. package/src/commands/users.js +269 -0
  27. package/src/config.js +49 -0
  28. package/src/context-store.js +37 -0
  29. package/src/credentials.js +285 -0
  30. package/src/deployment-api-auth.js +61 -0
  31. package/src/deployment-auth.js +38 -0
  32. package/src/deployments.js +26 -0
  33. package/src/discovery.js +66 -0
  34. package/src/env-compare.js +143 -0
  35. package/src/foundation-template.js +57 -0
  36. package/src/iam-session.js +67 -0
  37. package/src/migrations-lib.js +15 -0
  38. package/src/module-catalog.js +66 -0
  39. package/src/permissions-request.js +43 -0
  40. package/src/prompt.js +19 -0
  41. package/src/release-manifest.js +334 -0
  42. package/src/scope.js +114 -0
  43. package/src/settings.js +272 -0
  44. package/src/users-api.js +165 -0
  45. package/src/users-import/ids.js +24 -0
  46. package/src/users-import/import.js +292 -0
  47. package/src/users-import/manifest.js +90 -0
  48. package/src/users-import/providers/cognito.js +61 -0
  49. package/src/users-import/providers/index.js +24 -0
  50. package/templates/saaslayer-foundation-region.yml +109 -0
  51. package/templates/{host-account.yml → saaslayer-foundation.yml} +381 -87
@@ -0,0 +1,57 @@
1
+ // Deployable copy of the foundation template: whole-line comments stripped so it fits CloudFormation's
2
+ // 51,200-byte inline template limit (the documented source is larger), plus redaction for deploy argv in errors.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const os = require('os')
6
+ const path = require('path')
7
+
8
+ /** CloudFormation rejects inline (non-S3) templates larger than this many bytes. */
9
+ const CFN_INLINE_TEMPLATE_LIMIT = 51200
10
+
11
+ /**
12
+ * Removes whole-line YAML comments. The template keeps `#` only at line start for comments; content lines
13
+ * (folded Description text, URLs with fragments) are left untouched.
14
+ * @param {string} text
15
+ * @returns {string}
16
+ */
17
+ function stripComments(text) {
18
+ return text.split('\n').filter((line) => !/^\s*#/.test(line)).join('\n')
19
+ }
20
+
21
+ /**
22
+ * Writes the stripped template to a temp file and returns its path, for `aws cloudformation deploy --template-file`.
23
+ * @param {string} templatePath
24
+ * @returns {string}
25
+ */
26
+ function writeDeployableTemplate(templatePath) {
27
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'saaslayer-foundation-'))
28
+ const file = path.join(dir, path.basename(templatePath))
29
+ fs.writeFileSync(file, stripComments(fs.readFileSync(templatePath, 'utf8')))
30
+ return file
31
+ }
32
+
33
+ /**
34
+ * Deploy argv with the ExternalId override masked, for error messages and logs.
35
+ * @param {string[]} args
36
+ * @returns {string[]}
37
+ */
38
+ function redactArgs(args) {
39
+ return args.map((a) => (a.startsWith('ExternalId=') ? 'ExternalId=****' : a))
40
+ }
41
+
42
+ /**
43
+ * `aws cloudformation deploy` argv for `saaslayer init`, deploying the stripped template copy. A re-run that
44
+ * changes nothing is a clean no-op.
45
+ * @param {{ template: string, stackName: string, region: string, controlPlaneAccount: string, externalId: string, stackPrefix: string, orgId: string }} o
46
+ * @returns {string[]}
47
+ */
48
+ function initDeployArgs(o) {
49
+ return [
50
+ 'cloudformation', 'deploy', '--template-file', writeDeployableTemplate(o.template), '--stack-name', o.stackName, '--region', o.region,
51
+ '--capabilities', 'CAPABILITY_NAMED_IAM', '--no-fail-on-empty-changeset',
52
+ '--parameter-overrides',
53
+ `ControlPlaneAccountId=${o.controlPlaneAccount}`, `ExternalId=${o.externalId}`, `StackNamePrefix=${o.stackPrefix}`, `OrgId=${o.orgId}`,
54
+ ]
55
+ }
56
+
57
+ module.exports = { CFN_INLINE_TEMPLATE_LIMIT, stripComments, writeDeployableTemplate, redactArgs, initDeployArgs }
@@ -0,0 +1,67 @@
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
+ 'use strict'
4
+ const crypto = require('crypto')
5
+ const { execFileSync } = require('child_process')
6
+ const { signRequest } = require('./aws-sigv4')
7
+
8
+ /**
9
+ * Your current AWS credentials (env, profile, SSO) via the AWS CLI.
10
+ * @param {{ profile?: string }} [opts]
11
+ * @returns {{ accessKeyId: string, secretAccessKey: string, sessionToken?: string }}
12
+ */
13
+ function awsCredentials({ profile } = {}) {
14
+ const args = ['configure', 'export-credentials', '--format', 'process', ...(profile ? ['--profile', profile] : [])]
15
+ const c = JSON.parse(execFileSync('aws', args, { encoding: 'utf8' }))
16
+ return { accessKeyId: c.AccessKeyId, secretAccessKey: c.SecretAccessKey, sessionToken: c.SessionToken }
17
+ }
18
+
19
+ /**
20
+ * Signed STS GetCallerIdentity request binding the proof to `principalId` (and a one-time nonce).
21
+ * @param {{ principalId: string, region: string, credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date, nonce?: string }} opts
22
+ */
23
+ function buildStsEnvelope({ principalId, region, credentials, now = new Date(), nonce = crypto.randomUUID() }) {
24
+ const host = `sts.${region}.amazonaws.com`
25
+ const url = `https://${host}/`
26
+ const body = 'Action=GetCallerIdentity&Version=2011-06-15'
27
+ const { headers } = signRequest({
28
+ method: 'POST',
29
+ url,
30
+ body,
31
+ region,
32
+ service: 'sts',
33
+ credentials,
34
+ now,
35
+ headers: {
36
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
37
+ Host: host,
38
+ 'X-Saaslayer-Principal-Type': 'SERVICE_ACCOUNT',
39
+ 'X-Saaslayer-Principal-Id': principalId,
40
+ 'X-Saaslayer-Nonce': nonce,
41
+ 'X-Saaslayer-Timestamp': now.toISOString().replace(/\.\d{3}/, ''),
42
+ },
43
+ })
44
+ return { method: 'POST', url, headers, body }
45
+ }
46
+
47
+ /**
48
+ * Exchange your AWS identity for an iam_ token on the deployment's permissions API.
49
+ * @param {{ apiBase: string, principalId: string, region: string, credentials?: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, profile?: string }} opts
50
+ * @returns {Promise<string>}
51
+ */
52
+ async function exchangeIamToken({ apiBase, principalId, region, credentials, profile }) {
53
+ const envelope = buildStsEnvelope({ principalId, region, credentials: credentials || awsCredentials({ profile }) })
54
+ const res = await fetch(`${apiBase.replace(/\/$/, '')}/auth/aws-iam`, {
55
+ method: 'POST',
56
+ headers: { 'content-type': 'application/json' },
57
+ body: JSON.stringify({ principalId, envelope }),
58
+ })
59
+ const body = await res.json().catch(() => ({}))
60
+ if (!res.ok) {
61
+ const detail = (body.errors || []).map((e) => e.message).filter(Boolean).join('; ') || JSON.stringify(body)
62
+ throw new Error(`IAM exchange failed (${res.status}): ${detail}`)
63
+ }
64
+ return body.data.attributes.token
65
+ }
66
+
67
+ module.exports = { awsCredentials, buildStsEnvelope, exchangeIamToken }
@@ -0,0 +1,15 @@
1
+ // The per-service migration runner (@saaslayer/migrations, unpublished) that `saaslayer migrate` drives. Monorepo
2
+ // source first (vendor/ is a prepack snapshot that goes stale in a checkout); the published CLI carries vendor/migrations.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+
7
+ // Resolved at runtime because it is never shipped: present only in a monorepo checkout.
8
+ const MONOREPO_MIGRATIONS = path.join(__dirname, '../../migrations/src')
9
+ const VENDORED = path.join(__dirname, '../vendor/migrations')
10
+
11
+ function loadMigrations() {
12
+ return require(fs.existsSync(path.join(MONOREPO_MIGRATIONS, 'index.js')) ? MONOREPO_MIGRATIONS : VENDORED)
13
+ }
14
+
15
+ module.exports = { loadMigrations }
@@ -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 }
package/src/prompt.js ADDED
@@ -0,0 +1,19 @@
1
+ // Minimal interactive prompts for the CLI (confirm y/N + free text). readline-based; used by the deploy
2
+ // cost-confirm and the destroy typed-name confirmation. Non-interactive stdin resolves to '' (caller decides).
3
+ 'use strict'
4
+ const readline = require('readline')
5
+
6
+ function ask(question) {
7
+ return new Promise((resolve) => {
8
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY })
9
+ rl.question(question, (answer) => { rl.close(); resolve(String(answer || '').trim()) })
10
+ })
11
+ }
12
+
13
+ // y/N confirm — returns true only on an explicit yes.
14
+ async function confirm(question) {
15
+ const a = (await ask(`${question} [y/N] `)).toLowerCase()
16
+ return a === 'y' || a === 'yes'
17
+ }
18
+
19
+ module.exports = { ask, confirm }
@@ -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
+ }