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,261 @@
1
+ // `saaslayer login|logout|whoami` — authenticate via Cognito SRP (headless, D9) to the SaaSLayer control plane or, with
2
+ // --deployment, to a deployment's user-service (discovered from its public outputs), caching each login separately.
3
+ 'use strict'
4
+ const readline = require('readline')
5
+ const creds = require('../credentials')
6
+ const { resolvePoolConfig, decodeJwt, controlPlaneUrl } = require('../config')
7
+ const { discoverDeployment, discoverFromFlags } = require('../discovery')
8
+
9
+ // Prompt for a value; hidden masks input (passwords). Only used when no flag/env supplies it.
10
+ function prompt(question, { hidden = false, input = process.stdin, output = process.stdout } = {}) {
11
+ return new Promise((resolve) => {
12
+ const rl = readline.createInterface({ input, output, terminal: true })
13
+ if (hidden) {
14
+ // Suppress readline's own keystroke echo so only our mask shows (not char+mask interleaved).
15
+ rl._writeToOutput = () => {}
16
+ const onData = (char) => {
17
+ char = String(char)
18
+ if (char === '\u007f' || char === '\b') { output.write('\b \b'); return } // backspace
19
+ if (['\n', '\r', ''].includes(char)) return
20
+ output.write('*')
21
+ }
22
+ input.on('data', onData)
23
+ rl.question('', (answer) => { input.removeListener('data', onData); rl.close(); output.write('\n'); resolve(answer) })
24
+ // Written after question(''): readline's line redraw clears the row, which erased a question written first.
25
+ output.write(question)
26
+ } else {
27
+ rl.question(question, (answer) => { rl.close(); resolve(answer) })
28
+ }
29
+ })
30
+ }
31
+
32
+ /**
33
+ * @typedef {{ idToken: string, accessToken?: string, refreshToken?: string, expiresIn?: number }} LoginTokens
34
+ * @typedef {{ region: string, userPoolId: string, clientId: string }} PoolCoordinates
35
+ */
36
+
37
+ /**
38
+ * The tokens of a finished SRP step. A step the CLI cannot answer is refused with its name.
39
+ * @param {{ code?: string, error?: any, response?: { tokens: LoginTokens } }} value
40
+ * @returns {LoginTokens}
41
+ */
42
+ function tokensFromStep(value) {
43
+ if (value.code === 'ERROR') throw new Error(`login failed: ${(value.error && (value.error.message || value.error)) || 'unknown error'}`)
44
+ if (value.code !== 'TOKENS' || !value.response) {
45
+ throw new Error(`login requires the '${value.code}' step, which the CLI cannot answer; complete it in the hosted login page`)
46
+ }
47
+ return value.response.tokens
48
+ }
49
+
50
+ /** SRP challenge steps the CLI answers. */
51
+ const CHALLENGES = ['NEW_PASSWORD_REQUIRED', 'SOFTWARE_MFA_REQUIRED', 'SMS_MFA_REQUIRED']
52
+ const MAX_MFA_ATTEMPTS = 3
53
+
54
+ /**
55
+ * @typedef {{ isTTY: boolean, readStdin: () => Promise<string>, prompt: (question: string, opts?: { hidden?: boolean }) => Promise<string> }} LoginIo
56
+ * @typedef {{ code: string, hint?: string, error?: unknown }} ChallengeStep
57
+ */
58
+
59
+ /** @returns {Promise<string>} all of stdin */
60
+ async function readStdin() {
61
+ const chunks = []
62
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk))
63
+ return Buffer.concat(chunks).toString('utf8')
64
+ }
65
+
66
+ /** @type {LoginIo} */
67
+ const terminalIo = { get isTTY() { return Boolean(process.stdin.isTTY) }, readStdin, prompt }
68
+
69
+ /**
70
+ * The new password for NEW_PASSWORD_REQUIRED: piped on stdin with --new-password-stdin, else typed twice (hidden).
71
+ * @param {Record<string, any>} flags
72
+ * @param {LoginIo} io
73
+ * @returns {Promise<string>}
74
+ */
75
+ async function readNewPassword(flags, io) {
76
+ if (flags['new-password-stdin']) {
77
+ const piped = (await io.readStdin()).replace(/\r?\n$/, '')
78
+ if (!piped) throw new Error('new password read from stdin is empty')
79
+ return piped
80
+ }
81
+ if (!io.isTTY) throw new Error('this account requires a new password: pipe it with --new-password-stdin, or run login in a terminal')
82
+ const chosen = await io.prompt('New password: ', { hidden: true })
83
+ if (!chosen) throw new Error('new password is empty')
84
+ const confirmed = await io.prompt('Confirm new password: ', { hidden: true })
85
+ if (chosen !== confirmed) throw new Error('new passwords do not match')
86
+ return chosen
87
+ }
88
+
89
+ /**
90
+ * Answers the SRP challenges of one login from flags or the terminal. A code from --mfa-code is used once; when it
91
+ * is rejected the login fails. Typed codes are re-prompted up to MAX_MFA_ATTEMPTS. Answers are never printed.
92
+ * @param {Record<string, any>} flags --new-password-stdin, --mfa-code
93
+ * @param {LoginIo} io
94
+ * @returns {(step: ChallengeStep) => Promise<string>}
95
+ */
96
+ function challengeAnswerer(flags, io) {
97
+ let mfaAttempts = 0
98
+ let mfaFromFlag = false
99
+ return async (step) => {
100
+ if (step.code === 'NEW_PASSWORD_REQUIRED') return readNewPassword(flags, io)
101
+ const rejected = Boolean(step.error)
102
+ if (rejected && mfaFromFlag) throw new Error('MFA code was rejected')
103
+ if (rejected && mfaAttempts >= MAX_MFA_ATTEMPTS) throw new Error(`MFA code was rejected ${MAX_MFA_ATTEMPTS} times`)
104
+ if (flags['mfa-code'] !== undefined && !rejected) {
105
+ const code = flags['mfa-code']
106
+ if (typeof code !== 'string' || !/^\d{6}$/.test(code)) throw new Error('--mfa-code must be 6 digits')
107
+ mfaFromFlag = true
108
+ mfaAttempts++
109
+ return code
110
+ }
111
+ if (!io.isTTY) throw new Error('this account requires an MFA code: pass --mfa-code <6 digits>, or run login in a terminal')
112
+ const source = step.code === 'SMS_MFA_REQUIRED' ? `SMS code sent to ${step.hint || 'your phone'}` : 'MFA code from your authenticator app'
113
+ mfaAttempts++
114
+ return io.prompt(`${rejected ? 'Incorrect code. ' : ''}${source}: `, { hidden: true })
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Sign in to one Cognito pool client with SRP, answering NEW_PASSWORD_REQUIRED and MFA challenges from flags or the
120
+ * terminal. Both login authorities go through here.
121
+ * @param {PoolCoordinates} pool
122
+ * @param {{ email: string, password: string }} credentials
123
+ * @param {{ flags?: Record<string, any>, io?: LoginIo, srpLogin?: Function }} [opts]
124
+ * @returns {Promise<LoginTokens>}
125
+ */
126
+ async function authenticate(pool, { email, password }, { flags = {}, io = terminalIo, srpLogin } = {}) {
127
+ const run = srpLogin || require('@davidwells/cogneato').srpLogin
128
+ const steps = run({ region: pool.region, userPoolId: pool.userPoolId, clientId: pool.clientId, username: email, password })
129
+ const answer = challengeAnswerer(flags, io)
130
+ try {
131
+ let step = await steps.next()
132
+ while (!step.done && step.value && CHALLENGES.includes(step.value.code)) {
133
+ step = await steps.next(await answer(step.value))
134
+ }
135
+ return tokensFromStep(step.value || {})
136
+ } finally {
137
+ await steps.return(undefined)
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Email + password from flags, env or an interactive prompt.
143
+ * @param {Record<string, any>} flags
144
+ * @returns {Promise<{ email: string, password: string }>}
145
+ */
146
+ async function readCredentials(flags) {
147
+ const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
148
+ const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Password: ', { hidden: true }))
149
+ return { email, password }
150
+ }
151
+
152
+ /**
153
+ * Log in to the SaaSLayer control plane and make that account current. Deployment logins are not touched.
154
+ * @param {Record<string, any>} flags
155
+ * @param {{ authenticate?: typeof authenticate, srpLogin?: Function, io?: LoginIo }} [deps]
156
+ */
157
+ async function login(flags = {}, deps = {}) {
158
+ const pool = await resolvePoolConfig(flags)
159
+ const { email, password } = await readCredentials(flags)
160
+ const tokens = await (deps.authenticate || authenticate)(pool, { email, password }, { flags, io: deps.io, srpLogin: deps.srpLogin })
161
+ const claims = decodeJwt(tokens.idToken)
162
+ const userId = claims.sub
163
+ const expiresAt = Math.floor(Date.now() / 1000) + (Number(tokens.expiresIn) || 3600)
164
+ creds.setUser({
165
+ userId,
166
+ email: claims.email || email,
167
+ env: flags.env || 'prod',
168
+ issuer: claims.iss,
169
+ clientId: pool.clientId,
170
+ region: pool.region,
171
+ idToken: tokens.idToken,
172
+ accessToken: tokens.accessToken,
173
+ refreshToken: tokens.refreshToken,
174
+ expiresAt,
175
+ })
176
+ return { userId, email: claims.email || email }
177
+ }
178
+
179
+ /**
180
+ * `saaslayer login --deployment <dep_id|env>`: log in to a deployment's user-service (option B access admin).
181
+ * The pool, client and API bases come from the deployment's public discovery document; an environment name is first
182
+ * resolved to the project's deployment. The token must come from the discovered issuer and one of its app clients.
183
+ * The login is stored as its own profile and made the current deployment login; the control-plane login is kept.
184
+ * @param {Record<string, any>} flags --deployment, --user-service-instance, --region, --project, --config-url, --email, --password,
185
+ * --new-password-stdin, --mfa-code
186
+ * @param {{ authenticate?: typeof authenticate, discover?: typeof discoverDeployment, srpLogin?: Function, io?: LoginIo }} [deps]
187
+ */
188
+ async function loginDeployment(flags, deps = {}) {
189
+ const selector = flags.deployment
190
+ if (!selector || typeof selector !== 'string') throw new Error('login --deployment requires a deployment id (dep_…) or an environment name')
191
+ const { doc, deploymentId, environment, project } = await discoverFromFlags({ ...flags, 'discovery-url': undefined }, { discover: deps.discover })
192
+ const instance = flags['user-service-instance'] || null
193
+ const pool = { region: doc.region, userPoolId: doc.userPoolId, clientId: doc.clientId }
194
+ const { email, password } = await readCredentials(flags)
195
+ const tokens = await (deps.authenticate || authenticate)(pool, { email, password }, { flags, io: deps.io, srpLogin: deps.srpLogin })
196
+ const claims = decodeJwt(tokens.idToken)
197
+ if (claims.iss !== doc.issuer) throw new Error(`login token issuer ${claims.iss} does not match deployment ${deploymentId} (${doc.issuer})`)
198
+ if (!doc.audience.includes(claims.aud)) throw new Error(`login token audience ${claims.aud} is not a client of deployment ${deploymentId}`)
199
+ const profile = creds.setDeploymentProfile({
200
+ deploymentId,
201
+ serviceInstance: instance || 'default',
202
+ environment,
203
+ project,
204
+ userId: claims.sub,
205
+ suid: claims['custom:suid'] || null,
206
+ email: claims.email || email,
207
+ issuer: doc.issuer,
208
+ audience: doc.audience,
209
+ clientId: doc.clientId,
210
+ region: doc.region,
211
+ userPoolId: doc.userPoolId,
212
+ usersApiBase: doc.usersApiBase,
213
+ permissionsApiBase: doc.permissionsApiBase,
214
+ idToken: tokens.idToken,
215
+ accessToken: tokens.accessToken,
216
+ refreshToken: tokens.refreshToken,
217
+ expiresAt: Math.floor(Date.now() / 1000) + (Number(tokens.expiresIn) || 3600),
218
+ })
219
+ return { deploymentId, serviceInstance: profile.serviceInstance, environment, email: profile.email, userId: profile.userId }
220
+ }
221
+
222
+ // Create a SaaSLayer account via the control-plane signup endpoint (allowlist-gated), then log in.
223
+ async function signup(flags = {}) {
224
+ const base = String(controlPlaneUrl(flags).value).replace(/\/$/, '')
225
+ const email = flags.email || process.env.SAASLAYER_EMAIL || (await prompt('Email: '))
226
+ const password = flags.password || process.env.SAASLAYER_PASSWORD || (await prompt('Choose a password: ', { hidden: true }))
227
+ const res = await fetch(`${base}/api/signup`, {
228
+ method: 'POST',
229
+ headers: { 'content-type': 'application/json' },
230
+ body: JSON.stringify({ email, password }),
231
+ })
232
+ const doc = await res.json().catch(() => ({}))
233
+ if (!res.ok) throw new Error(`signup failed (${res.status}): ${doc.error || JSON.stringify(doc)}`)
234
+ // Log in immediately so the account is usable right away.
235
+ return login({ ...flags, email, password })
236
+ }
237
+
238
+ function whoami() {
239
+ const current = creds.getCurrent()
240
+ if (!current) return null
241
+ return { userId: current.userId, email: current.email, env: current.env }
242
+ }
243
+
244
+ /**
245
+ * Clear one login on the selected authority. With --deployment (and --as / --user-service-instance) the matching
246
+ * deployment login is removed; otherwise the control-plane account (--user accepts an email or a userId; without it,
247
+ * the active account). The other authority's logins are kept.
248
+ * @param {Record<string, any>} flags
249
+ * @returns {{ authority: 'deployment', deploymentId: string, email: string|null } | { authority: 'control-plane' }}
250
+ */
251
+ function logout(flags = {}) {
252
+ if (flags.deployment || flags.as || flags['user-service-instance']) {
253
+ const profile = creds.selectDeploymentProfile(flags)
254
+ creds.clearDeploymentProfile(profile.key)
255
+ return { authority: 'deployment', deploymentId: profile.deploymentId, email: profile.email }
256
+ }
257
+ creds.clear(flags.user ? creds.resolve(flags.user) : undefined)
258
+ return { authority: 'control-plane' }
259
+ }
260
+
261
+ module.exports = { login, loginDeployment, authenticate, tokensFromStep, signup, whoami, logout, prompt }
@@ -0,0 +1,96 @@
1
+ // `saaslayer permissions machine-trust list|get|declare|update|remove|reconcile`: the deployment's trusted AWS IAM roles
2
+ // through the permissions machine-trust API (access-admin login, API key or IAM) — never a direct SSM write.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { permissionsRequest } = require('../permissions-request')
6
+
7
+ /**
8
+ * @typedef {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string,
9
+ * 'role-arn'?: string, scope?: string|string[], 'expected-revision'?: string, 'dry-run'?: boolean }} MachineTrustFlags
10
+ * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
11
+ */
12
+
13
+ /** @param {string} label @param {string[]} positional */
14
+ function principalIdOf(label, positional) {
15
+ if (!positional[0]) throw new Error(`${label}: <principalId> is required`)
16
+ return positional[0]
17
+ }
18
+
19
+ /** @param {MachineTrustFlags} flags @returns {string[]|undefined} */
20
+ function scopesOf(flags) {
21
+ if (flags.scope === undefined) return undefined
22
+ return Array.isArray(flags.scope) ? flags.scope : [flags.scope]
23
+ }
24
+
25
+ /** Call a machine-trust route; throws with the API's codes and messages. */
26
+ const call = permissionsRequest
27
+
28
+ /** @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps] */
29
+ async function machineTrustList(positional, flags, deps = {}) {
30
+ const body = await call('permissions machine-trust list', flags, deps, 'GET', '/machine-trust')
31
+ return (body.data || []).map((d) => d.attributes)
32
+ }
33
+
34
+ /** @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps] */
35
+ async function machineTrustGet(positional, flags, deps = {}) {
36
+ const id = principalIdOf('permissions machine-trust get', positional)
37
+ const body = await call('permissions machine-trust get', flags, deps, 'GET', `/machine-trust/${encodeURIComponent(id)}`)
38
+ return body.data.attributes
39
+ }
40
+
41
+ /**
42
+ * Declare a trusted role: <principalId> --role-arn ARN --scope S [--scope S2]. Creates no grant.
43
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
44
+ */
45
+ async function machineTrustDeclare(positional, flags, deps = {}) {
46
+ const label = 'permissions machine-trust declare'
47
+ const principalId = principalIdOf(label, positional)
48
+ if (!flags['role-arn']) throw new Error(`${label}: --role-arn <arn> is required`)
49
+ const scopeCeiling = scopesOf(flags)
50
+ if (!scopeCeiling) throw new Error(`${label}: at least one --scope is required`)
51
+ const body = await call(label, flags, deps, 'POST', '/machine-trust', { principalId, roleArn: flags['role-arn'], scopeCeiling })
52
+ return { declaration: body.data.attributes, meta: body.meta || {} }
53
+ }
54
+
55
+ /**
56
+ * Change a declaration: <principalId> [--role-arn ARN] [--scope S …] [--expected-revision N].
57
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
58
+ */
59
+ async function machineTrustUpdate(positional, flags, deps = {}) {
60
+ const label = 'permissions machine-trust update'
61
+ const principalId = principalIdOf(label, positional)
62
+ const scopeCeiling = scopesOf(flags)
63
+ if (!flags['role-arn'] && !scopeCeiling) throw new Error(`${label}: give --role-arn and/or --scope`)
64
+ /** @type {{ roleArn?: string, scopeCeiling?: string[], expectedRevision?: number }} */
65
+ const patch = {}
66
+ if (flags['role-arn']) patch.roleArn = flags['role-arn']
67
+ if (scopeCeiling) patch.scopeCeiling = scopeCeiling
68
+ if (flags['expected-revision'] !== undefined) {
69
+ const n = Number(flags['expected-revision'])
70
+ if (!Number.isInteger(n)) throw new Error(`${label}: --expected-revision must be an integer`)
71
+ patch.expectedRevision = n
72
+ }
73
+ const body = await call(label, flags, deps, 'PATCH', `/machine-trust/${encodeURIComponent(principalId)}`, patch)
74
+ return { declaration: body.data.attributes, meta: body.meta || {} }
75
+ }
76
+
77
+ /**
78
+ * Remove a declaration (its mapped principal's roles are unassigned; the report lists each).
79
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
80
+ */
81
+ async function machineTrustRemove(positional, flags, deps = {}) {
82
+ const id = principalIdOf('permissions machine-trust remove', positional)
83
+ const body = await call('permissions machine-trust remove', flags, deps, 'DELETE', `/machine-trust/${encodeURIComponent(id)}`)
84
+ return body.data.attributes
85
+ }
86
+
87
+ /**
88
+ * Rewrite the deployment's backing SSM document from the declarations.
89
+ * @param {string[]} positional @param {MachineTrustFlags} flags @param {Deps} [deps]
90
+ */
91
+ async function machineTrustReconcile(positional, flags, deps = {}) {
92
+ const body = await call('permissions machine-trust reconcile', flags, deps, 'POST', '/machine-trust/actions/reconcile', {})
93
+ return body.data.attributes
94
+ }
95
+
96
+ module.exports = { machineTrustList, machineTrustGet, machineTrustDeclare, machineTrustUpdate, machineTrustRemove, machineTrustReconcile }
@@ -0,0 +1,290 @@
1
+ // `saaslayer migrate status|plan|dry-run|up|report` (plan §2.17.9, D-Q11): run a self-run deployment's data migrations
2
+ // with the customer's own AWS credentials through @saaslayer/migrations, then report each service's ledger up to the CP.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const { execFileSync } = require('child_process')
7
+ const { apiCall } = require('../api-client')
8
+ const { loadMigrations } = require('../migrations-lib')
9
+
10
+ const SUBCOMMANDS = ['status', 'plan', 'dry-run', 'up', 'report']
11
+ const PROTECTED_ENVIRONMENTS = new Set(['prod', 'staging'])
12
+ const LEDGER_OUTPUT = 'MigrationsLedgerTableName'
13
+ const ROLE_OUTPUT = 'MigrateRoleArn'
14
+ const SESSION_PREFIX = 'saaslayer-migrate'
15
+ const DEFAULT_TIMEOUT_MINUTES = 60
16
+ const REFRESH_BEFORE_MS = 5 * 60 * 1000
17
+ // Report statuses that mean the service's migrations did not complete (the runner's run-level block codes + FAILED).
18
+ const FAILED_STATUSES = new Set(['FAILED', 'BLOCKED_NO_BACKUP', 'MIGRATION_LOCKED', 'MIGRATION_TOO_LARGE'])
19
+
20
+ /** @param {string} cmd @param {string[]} args @param {{ cwd?: string }} [opts] */
21
+ const defaultExec = (cmd, args, opts = {}) => execFileSync(cmd, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, ...opts })
22
+
23
+ /**
24
+ * @param {string} code
25
+ * @param {string} message
26
+ */
27
+ function cliError(code, message) {
28
+ return Object.assign(new Error(`${code}: ${message}`), { code })
29
+ }
30
+
31
+ /**
32
+ * The customer's own AWS credentials (default chain, or --profile) through the aws CLI, re-read 5 minutes before they
33
+ * expire. They are only the source of the migrate-role hop; migration code never sees them.
34
+ * @param {{ profile?: string, exec?: typeof defaultExec, now?: () => number }} p
35
+ * @returns {() => Promise<{ accessKeyId: string, secretAccessKey: string, sessionToken?: string, expiration?: Date }>}
36
+ */
37
+ function customerCredentials({ profile, exec = defaultExec, now = Date.now }) {
38
+ /** @type {{ accessKeyId: string, secretAccessKey: string, sessionToken?: string, expiration?: Date }|undefined} */
39
+ let current
40
+ return async function customerSession() {
41
+ if (current && (!current.expiration || current.expiration.getTime() - now() > REFRESH_BEFORE_MS)) return current
42
+ const out = JSON.parse(exec('aws', ['configure', 'export-credentials', '--format', 'process', ...(profile ? ['--profile', profile] : [])]))
43
+ current = {
44
+ accessKeyId: out.AccessKeyId,
45
+ secretAccessKey: out.SecretAccessKey,
46
+ ...(out.SessionToken ? { sessionToken: out.SessionToken } : {}),
47
+ ...(out.Expiration ? { expiration: new Date(out.Expiration) } : {}),
48
+ }
49
+ return current
50
+ }
51
+ }
52
+
53
+ /**
54
+ * The command's exit code across services: 1 failed > 3 applied but not reported > 2 awaiting approval > 0 ok.
55
+ * @param {Array<{ status: string, reported?: boolean|null }>} results
56
+ */
57
+ function exitCodeFor(results) {
58
+ if (results.some((r) => FAILED_STATUSES.has(r.status))) return 1
59
+ if (results.some((r) => r.reported === false)) return 3
60
+ if (results.some((r) => r.status === 'awaiting-approval')) return 2
61
+ return 0
62
+ }
63
+
64
+ /** @param {string} dir */
65
+ function loadContract(dir) {
66
+ const file = path.join(dir, 'saaslayer.module.js')
67
+ if (!fs.existsSync(file)) return null
68
+ return require(file)
69
+ }
70
+
71
+ /**
72
+ * The deployment facts the runner needs, from the control plane (deployment mode) or the flags (standalone --stack).
73
+ * `blocked` is an UPDATE halted on MIGRATION_PENDING_SELF_RUN: its target commit's pre-deploy migrations may run.
74
+ * @returns {Promise<{ deploymentId: string|null, environment: string|null, region: string, accountId: string|null, policy: string, protected: boolean, blocked: { runId: string, targetCommitSha: string, services: Record<string, string[]> }|null, services: Array<{ ref: string, stackName: string, dir: string, servicePath: string|null, commitSha: string|null }> }>}
75
+ */
76
+ async function resolveTarget(flags, repo, sub) {
77
+ if (flags.deployment) {
78
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(flags.deployment)}`, undefined, flags)
79
+ const d = (doc && doc.data && doc.data.attributes) || {}
80
+ if ((sub === 'up' || sub === 'report') && d.migrationRunner !== 'self') {
81
+ throw cliError('MIGRATION_RUNNER_NOT_SELF', `${flags.deployment} runs its migrations through the deployer (migrationRunner is ${d.migrationRunner || 'deployer'}); set migrationRunner self first`)
82
+ }
83
+ const isProtected = PROTECTED_ENVIRONMENTS.has(d.environment)
84
+ return {
85
+ deploymentId: flags.deployment,
86
+ environment: d.environment || null,
87
+ region: d.region,
88
+ accountId: d.accountId || null,
89
+ policy: d.migrationApproval || (isProtected ? 'destructive' : 'auto'),
90
+ protected: isProtected,
91
+ blocked: d.selfRunPendingUpdate || null,
92
+ services: (d.modules || []).map((m) => ({
93
+ ref: m.ref || m.moduleName,
94
+ stackName: m.stackName,
95
+ servicePath: m.servicePath || null,
96
+ dir: path.join(repo, m.servicePath || ''),
97
+ commitSha: m.runtimeCommitSha || m.deployedCommitSha || null,
98
+ })),
99
+ }
100
+ }
101
+ if (flags.stack) {
102
+ if (sub === 'report') throw cliError('USAGE', 'report sends to the control plane; standalone --stack mode has none')
103
+ if (!flags.region) throw cliError('USAGE', 'standalone mode needs --region with --stack')
104
+ const contract = loadContract(repo)
105
+ // No environment in standalone mode: destructive migrations wait for --approve-destructive; no backup requirement.
106
+ return {
107
+ deploymentId: null,
108
+ environment: null,
109
+ region: flags.region,
110
+ accountId: null,
111
+ policy: 'destructive',
112
+ protected: false,
113
+ blocked: null,
114
+ services: [{ ref: (contract && contract.name) || flags.stack, stackName: flags.stack, servicePath: null, dir: repo, commitSha: null }],
115
+ }
116
+ }
117
+ throw cliError('USAGE', 'pass --deployment <id> (control plane) or --stack <name> --region <r> (standalone)')
118
+ }
119
+
120
+ /**
121
+ * @param {'status'|'plan'|'dry-run'|'up'|'report'} sub
122
+ * @param {Record<string, any>} flags
123
+ * @param {{ exec?: typeof defaultExec, log?: (line: string) => void, now?: () => number, existsSync?: (p: string) => boolean,
124
+ * migrations?: { runServiceMigrations: Function, readLedgerReport: Function }, runnerDeps?: object, endpoint?: string,
125
+ * onOutput?: (chunk: string) => void }} [deps]
126
+ * @returns {Promise<{ exitCode: number, services: Array<{ serviceRef: string, status: string, reported: boolean|null, report: any }> }>}
127
+ */
128
+ async function migrate(sub, flags, deps = {}) {
129
+ const exec = deps.exec || defaultExec
130
+ const log = deps.log || ((line) => console.log(line))
131
+ const now = deps.now || Date.now
132
+ const existsSync = deps.existsSync || fs.existsSync
133
+ const onOutput = deps.onOutput || ((chunk) => process.stderr.write(chunk))
134
+ if (!SUBCOMMANDS.includes(sub)) throw cliError('USAGE', `saaslayer migrate <${SUBCOMMANDS.join('|')}> (see saaslayer --help)`)
135
+ if (flags['approve-destructive'] && (typeof flags.reason !== 'string' || !flags.reason.trim())) {
136
+ throw cliError('USAGE', '--approve-destructive needs --reason <text>')
137
+ }
138
+ const lib = deps.migrations || loadMigrations()
139
+ const repo = path.resolve(typeof flags.repo === 'string' ? flags.repo : process.cwd())
140
+ const target = await resolveTarget(flags, repo, sub)
141
+
142
+ let services = target.services
143
+ if (flags.service) {
144
+ services = services.filter((s) => s.ref === flags.service)
145
+ if (services.length === 0) throw cliError('USAGE', `service ${flags.service} is not on ${target.deploymentId || target.services[0].stackName}`)
146
+ }
147
+ let migrating = services
148
+ .map((s) => ({ ...s, contract: loadContract(s.dir) }))
149
+ .filter((s) => s.contract && s.contract.migrations)
150
+
151
+ // Run exactly the deployed migrations: the checkout must be at each service's deployed commit, migrations untouched.
152
+ // While an UPDATE is blocked on self-run pre-deploy migrations, its target commit may run those (phase pre) instead.
153
+ let phase = 'all'
154
+ if (target.deploymentId) {
155
+ const head = exec('git', ['-C', repo, 'rev-parse', 'HEAD']).trim()
156
+ const atBlockedTarget = Boolean(target.blocked && head === target.blocked.targetCommitSha && migrating.some((s) => s.commitSha !== head))
157
+ if (atBlockedTarget) {
158
+ phase = 'pre'
159
+ migrating = migrating.map((s) => ({ ...s, commitSha: head }))
160
+ log(`update ${target.blocked.runId} is waiting on pre-deploy migrations at ${head}: running only those`)
161
+ }
162
+ for (const s of migrating) {
163
+ if (s.commitSha !== head) {
164
+ const blockedHint = target.blocked ? ` or the blocked update's target ${target.blocked.targetCommitSha}` : ''
165
+ throw cliError('MIGRATION_SOURCE_MISMATCH', `${s.ref}: checkout is at ${head}, not the deployed commit ${s.commitSha || '(none)'}${blockedHint}; check out that commit first`)
166
+ }
167
+ const changed = exec('git', ['-C', repo, 'status', '--porcelain', '--', path.join(s.servicePath || '', s.contract.migrations.dir)]).trim()
168
+ if (changed) throw cliError('MIGRATION_SOURCE_MISMATCH', `${s.ref}: uncommitted changes under ${s.contract.migrations.dir}/`)
169
+ }
170
+ }
171
+
172
+ const awsArgs = ['--region', target.region, ...(flags.profile ? ['--profile', flags.profile] : [])]
173
+ const caller = JSON.parse(exec('aws', ['sts', 'get-caller-identity', '--output', 'json', ...awsArgs]))
174
+ const callerArn = caller.Arn
175
+ const sourceCredentials = customerCredentials({ profile: flags.profile, exec, now })
176
+ const runId = `cli-${now()}`
177
+ const run = { runId, appliedBy: `saaslayer-cli:${callerArn}`, source: 'self', commitSha: undefined, lockOwner: `saaslayer-cli:${callerArn}:${now()}` }
178
+ const results = []
179
+
180
+ for (const s of migrating) {
181
+ const { migrations } = s.contract
182
+ // As the deployer does: a migration's requires resolve from the service's own deps.
183
+ if (!existsSync(path.join(s.dir, 'node_modules')) && existsSync(path.join(s.dir, 'package-lock.json'))) {
184
+ exec('npm', ['ci'], { cwd: s.dir })
185
+ }
186
+ const outputs = Object.fromEntries((JSON.parse(exec('aws', ['cloudformation', 'describe-stacks', '--stack-name', s.stackName, '--query', 'Stacks[0].Outputs', '--output', 'json', ...awsArgs])) || [])
187
+ .map((o) => [o.OutputKey, o.OutputValue]))
188
+ const tables = {}
189
+ for (const [logical, outputKey] of Object.entries(migrations.tables || {})) {
190
+ // Pre: a table the target release adds does not exist yet; the loader refuses a pre migration that targets it.
191
+ if (!outputs[outputKey] && phase === 'pre') continue
192
+ if (!outputs[outputKey]) throw cliError('MIGRATION_TABLE_OUTPUT_MISSING', `${s.ref}: migrations.tables.${logical}: no ${outputKey} output on ${s.stackName}`)
193
+ tables[logical] = outputs[outputKey]
194
+ }
195
+ const stage = target.deploymentId || s.stackName
196
+ const opts = {
197
+ service: { ref: s.ref, dir: s.dir, migrationsDir: migrations.dir, tables },
198
+ ledger: { tableName: outputs[LEDGER_OUTPUT], scope: s.ref, stage },
199
+ role: { roleArn: outputs[ROLE_OUTPUT], sourceCredentials, sessionPrefix: SESSION_PREFIX },
200
+ region: target.region,
201
+ accountId: target.accountId || caller.Account || undefined,
202
+ ...(deps.endpoint ? { endpoint: deps.endpoint } : {}),
203
+ phase,
204
+ mode: sub === 'dry-run' ? 'dry-run' : sub === 'up' ? 'apply' : 'plan',
205
+ gate: { policy: target.policy, protected: target.protected, approval: null },
206
+ run: { ...run, commitSha: s.commitSha || undefined },
207
+ params: {
208
+ ...(target.deploymentId ? { deploymentId: target.deploymentId } : {}),
209
+ environment: target.environment, protected: target.protected, serviceRef: s.ref, stackName: s.stackName,
210
+ region: target.region, accountId: target.accountId || caller.Account || undefined, runId, source: 'self',
211
+ },
212
+ timeoutSeconds: (migrations.timeoutMinutes || DEFAULT_TIMEOUT_MINUTES) * 60,
213
+ onOutput,
214
+ }
215
+ if (!target.deploymentId) delete opts.params.deploymentId
216
+
217
+ if (sub === 'status' || sub === 'report') {
218
+ const report = await lib.readLedgerReport(opts, deps.runnerDeps)
219
+ const reported = sub === 'report' ? await sendReport({ flags, target, report, log }) : null
220
+ results.push({ serviceRef: s.ref, status: report.status, reported, report })
221
+ continue
222
+ }
223
+ if (sub === 'up' && flags['approve-destructive']) {
224
+ const planned = await lib.runServiceMigrations({ ...opts, mode: 'plan' }, deps.runnerDeps)
225
+ const items = (planned.migrations || [])
226
+ .filter((m) => target.policy === 'all' || m.destructive)
227
+ .map((m) => ({ serviceRef: s.ref, id: m.id, checksum: m.checksum }))
228
+ opts.gate = { ...opts.gate, approval: { runId, approver: callerArn, reason: flags.reason, items } }
229
+ }
230
+ const report = await lib.runServiceMigrations(opts, deps.runnerDeps)
231
+ let reported = null
232
+ if (sub === 'up' && target.deploymentId) {
233
+ // Sent after the ledger rows are final. A lost report never re-applies or fails anything: re-send from the ledger.
234
+ const inventory = await lib.readLedgerReport(opts, deps.runnerDeps)
235
+ if (inventory.error) {
236
+ log(`${s.ref}: could not re-read the ledger for the report (${inventory.error.code}); run \`saaslayer migrate report\``)
237
+ reported = false
238
+ } else {
239
+ const { reportError, ...ledgerReport } = report
240
+ reported = await sendReport({ flags, target, report: { ...ledgerReport, appliedMigrations: inventory.appliedMigrations }, log })
241
+ }
242
+ }
243
+ results.push({ serviceRef: s.ref, status: report.status, reported, report })
244
+ }
245
+
246
+ for (const r of results) printResult(r, log, flags.json)
247
+ const exitCode = exitCodeFor(results)
248
+ if (flags.json) log(JSON.stringify({ exitCode, services: results }, null, 2))
249
+ else if (results.length === 0) log('no service with migrations in this checkout')
250
+ return { exitCode, services: results }
251
+ }
252
+
253
+ /**
254
+ * POST one service's report. Returns false (never throws) when the control plane did not take it.
255
+ * @returns {Promise<boolean|null>} null = nothing to report (no ledger discovered)
256
+ */
257
+ async function sendReport({ flags, target, report, log }) {
258
+ if (!report.ledger || !report.ledger.tableName) return null
259
+ try {
260
+ const res = await apiCall('POST', `/api/deployments/${encodeURIComponent(target.deploymentId)}/migrations/reports`, { data: { type: 'migration-reports', attributes: report } }, flags)
261
+ const recorded = (res && res.data && res.data.attributes) || {}
262
+ // A report that completes a blocked update's pre-deploy migrations restarts that update.
263
+ if (recorded.resumed && recorded.resumed.statusCode < 300) log(`update resumed: ${recorded.resumed.runId || recorded.resumed.status}`)
264
+ else if (recorded.resumed) log(`update not resumed (${recorded.resumed.error || recorded.resumed.status}); run \`saaslayer update\` to the target commit`)
265
+ else if (recorded.waitingFor && Object.keys(recorded.waitingFor).length > 0) log(`update still waiting on: ${Object.entries(recorded.waitingFor).map(([ref, ids]) => `${ref} (${ids.join(', ')})`).join('; ')}`)
266
+ return true
267
+ } catch (err) {
268
+ log(`${report.serviceRef}: report not sent (${err.message}). The migrations stay as the ledger records them; run \`saaslayer migrate report\` to re-send.`)
269
+ return false
270
+ }
271
+ }
272
+
273
+ /**
274
+ * @param {{ serviceRef: string, status: string, reported: boolean|null, report: any }} r
275
+ * @param {(line: string) => void} log
276
+ * @param {boolean} [json]
277
+ */
278
+ function printResult(r, log, json) {
279
+ if (json) return
280
+ const sent = r.reported === true ? ' reported' : r.reported === false ? ' NOT reported' : ''
281
+ log(`${r.serviceRef}: ${r.status}${sent}`)
282
+ if (r.report.error) log(` ${r.report.error.code}: ${r.report.error.message}`)
283
+ for (const m of r.report.migrations || []) {
284
+ const c = m.counts || {}
285
+ log(` ${m.id} ${m.status}${m.destructive ? ' destructive' : ''} wouldWrite=${c.wouldWrite || 0} written=${c.written || 0}${m.error ? ` ${m.error.code}` : ''}`)
286
+ }
287
+ if (r.report.appliedMigrations) log(` applied: ${r.report.appliedMigrations.length}`)
288
+ }
289
+
290
+ module.exports = { migrate, customerCredentials, exitCodeFor, SUBCOMMANDS }