saaslayer 0.0.7 → 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 (44) hide show
  1. package/README.md +150 -13
  2. package/bin/saaslayer.js +297 -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/catalog.js +30 -29
  10. package/src/commands/context.js +64 -0
  11. package/src/commands/deploy.js +79 -10
  12. package/src/commands/first-admin.js +42 -0
  13. package/src/commands/foundation.js +405 -0
  14. package/src/commands/lifecycle.js +72 -39
  15. package/src/commands/login.js +200 -26
  16. package/src/commands/machine-trust.js +96 -0
  17. package/src/commands/operations.js +140 -0
  18. package/src/commands/orgs.js +29 -4
  19. package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
  20. package/src/commands/release-manifest.js +138 -0
  21. package/src/commands/service-principals.js +81 -0
  22. package/src/commands/settings.js +140 -0
  23. package/src/commands/stacks.js +12 -7
  24. package/src/commands/users.js +192 -4
  25. package/src/config.js +20 -7
  26. package/src/credentials.js +221 -34
  27. package/src/deployment-api-auth.js +61 -0
  28. package/src/deployment-auth.js +38 -0
  29. package/src/deployments.js +12 -13
  30. package/src/discovery.js +66 -0
  31. package/src/env-compare.js +143 -0
  32. package/src/iam-session.js +4 -30
  33. package/src/module-catalog.js +66 -0
  34. package/src/permissions-request.js +43 -0
  35. package/src/release-manifest.js +334 -0
  36. package/src/scope.js +114 -0
  37. package/src/settings.js +272 -0
  38. package/src/users-api.js +165 -0
  39. package/src/users-import/import.js +10 -10
  40. package/templates/saaslayer-foundation.yml +23 -6
  41. package/src/commands/iam-principals.js +0 -53
  42. package/src/rbac-auth.js +0 -25
  43. package/vendor/ids/index.d.ts +0 -21
  44. package/vendor/ids/index.js +0 -237
@@ -1,9 +1,23 @@
1
- // Local credential store for the saaslayer CLI. Persists Cognito tokens per SaaSLayer account under
2
- // ~/.saaslayer/credentials.json (0600), keyed by userId, with a `current` pointer for the active one.
1
+ // Local credential store for the saaslayer CLI, one profile set per authority: control-plane logins (keyed by userId)
2
+ // and deployment logins (keyed by deployment/user-service instance/user), each with its own `current` pointer (0600).
3
3
  'use strict'
4
4
  const fs = require('fs')
5
5
  const os = require('os')
6
6
  const path = require('path')
7
+ const { decodeJwt } = require('./config')
8
+
9
+ const STORE_VERSION = 2
10
+
11
+ /**
12
+ * @typedef {{ userId: string, email?: string, env?: string, issuer?: string, clientId?: string, region?: string,
13
+ * idToken?: string, accessToken?: string, refreshToken?: string|null, expiresAt?: number, lastUsedAt?: number }} ControlPlaneProfile
14
+ * @typedef {{ key: string, deploymentId: string, serviceInstance: string, environment: string|null, project: string|null,
15
+ * userId: string, suid: string|null, email: string|null, issuer: string, audience: string[], clientId: string,
16
+ * region: string, userPoolId: string, usersApiBase: string, permissionsApiBase: string, idToken: string, accessToken?: string,
17
+ * refreshToken?: string|null, expiresAt: number, lastUsedAt?: number }} DeploymentProfile
18
+ * @typedef {{ version: number, controlPlane: { profiles: Record<string, ControlPlaneProfile>, current: string|null },
19
+ * deployments: { profiles: Record<string, DeploymentProfile>, current: string|null } }} Store
20
+ */
7
21
 
8
22
  // The store dir is overridable (SAASLAYER_HOME) so CI and tests never touch a real home directory.
9
23
  function storeDir() {
@@ -13,54 +27,111 @@ function storePath() {
13
27
  return path.join(storeDir(), 'credentials.json')
14
28
  }
15
29
 
16
- // Read the store; a missing or unreadable/corrupt file yields an empty store (never throws).
30
+ /** @returns {Store} */
31
+ function emptyStore() {
32
+ return { version: STORE_VERSION, controlPlane: { profiles: {}, current: null }, deployments: { profiles: {}, current: null } }
33
+ }
34
+
35
+ /**
36
+ * The issuer, app client and region a cached id token was minted by, read from its own claims.
37
+ * @param {string|undefined} idToken
38
+ * @returns {{ issuer?: string, clientId?: string, region?: string }}
39
+ */
40
+ function bindingFromToken(idToken) {
41
+ try {
42
+ const claims = decodeJwt(idToken)
43
+ const region = /^https:\/\/cognito-idp\.([a-z0-9-]+)\.amazonaws\.com\//.exec(String(claims.iss || ''))
44
+ return {
45
+ ...(claims.iss ? { issuer: claims.iss } : {}),
46
+ ...(typeof claims.aud === 'string' ? { clientId: claims.aud } : {}),
47
+ ...(region ? { region: region[1] } : {}),
48
+ }
49
+ } catch (err) {
50
+ return {}
51
+ }
52
+ }
53
+
54
+ /**
55
+ * The single-`current` file ({ users, current }) as control-plane profiles, each bound to its token's issuer/client.
56
+ * @param {{ users?: Record<string, ControlPlaneProfile>, current?: string|null }} parsed
57
+ * @returns {Store}
58
+ */
59
+ function migrateSingleCurrent(parsed) {
60
+ const store = emptyStore()
61
+ for (const [userId, user] of Object.entries(parsed.users || {})) {
62
+ store.controlPlane.profiles[userId] = { ...bindingFromToken(user.idToken), ...user }
63
+ }
64
+ store.controlPlane.current = parsed.current || null
65
+ return store
66
+ }
67
+
68
+ /**
69
+ * Read the store; a missing or unreadable/corrupt file yields an empty store (never throws). A single-`current` file
70
+ * is migrated and rewritten in place on first read.
71
+ * @returns {Store}
72
+ */
17
73
  function load() {
74
+ let parsed
18
75
  try {
19
- const raw = fs.readFileSync(storePath(), 'utf8')
20
- const parsed = JSON.parse(raw)
21
- if (!parsed || typeof parsed !== 'object') return { users: {}, current: null }
22
- return { users: parsed.users || {}, current: parsed.current || null }
76
+ parsed = JSON.parse(fs.readFileSync(storePath(), 'utf8'))
23
77
  } catch (err) {
24
- return { users: {}, current: null }
78
+ return emptyStore()
79
+ }
80
+ if (!parsed || typeof parsed !== 'object') return emptyStore()
81
+ if (parsed.version !== STORE_VERSION) {
82
+ const migrated = migrateSingleCurrent(parsed)
83
+ save(migrated)
84
+ return migrated
85
+ }
86
+ return {
87
+ version: STORE_VERSION,
88
+ controlPlane: { profiles: (parsed.controlPlane && parsed.controlPlane.profiles) || {}, current: (parsed.controlPlane && parsed.controlPlane.current) || null },
89
+ deployments: { profiles: (parsed.deployments && parsed.deployments.profiles) || {}, current: (parsed.deployments && parsed.deployments.current) || null },
25
90
  }
26
91
  }
27
92
 
28
- // Write the store atomically with 0600 perms so tokens are not world-readable.
93
+ /**
94
+ * Write the store atomically with 0600 perms so tokens are not world-readable.
95
+ * @param {Store} store
96
+ */
29
97
  function save(store) {
30
98
  const dir = storeDir()
31
99
  fs.mkdirSync(dir, { recursive: true })
32
100
  const tmp = path.join(dir, `.credentials.${process.pid}.tmp`)
33
- const body = JSON.stringify({ users: store.users || {}, current: store.current || null }, null, 2)
101
+ const body = JSON.stringify({ version: STORE_VERSION, controlPlane: store.controlPlane, deployments: store.deployments }, null, 2)
34
102
  fs.writeFileSync(tmp, body, { mode: 0o600 })
35
103
  fs.renameSync(tmp, storePath())
36
104
  try { fs.chmodSync(storePath(), 0o600) } catch (err) { /* best-effort on platforms without chmod */ }
37
105
  }
38
106
 
39
- // Upsert an account and make it current. `record` carries { userId, email, env, idToken, accessToken,
40
- // refreshToken, expiresAt }. Stamps lastUsedAt so `list` can order most-recently-used first.
107
+ // ---- control-plane logins -------------------------------------------------------------------------------------------
108
+
109
+ // Upsert a control-plane account and make it current. `record` carries { userId, email, env, issuer, clientId, region,
110
+ // idToken, accessToken, refreshToken, expiresAt }. Stamps lastUsedAt so `list` can order most-recently-used first.
41
111
  function setUser(record) {
42
112
  if (!record || !record.userId) throw new Error('setUser requires a userId')
43
113
  const store = load()
44
- store.users[record.userId] = { ...store.users[record.userId], ...record, lastUsedAt: Date.now() }
45
- store.current = record.userId
114
+ const profiles = store.controlPlane.profiles
115
+ profiles[record.userId] = { ...profiles[record.userId], ...record, lastUsedAt: Date.now() }
116
+ store.controlPlane.current = record.userId
46
117
  save(store)
47
- return store.users[record.userId]
118
+ return profiles[record.userId]
48
119
  }
49
120
 
50
121
  function getCurrent() {
51
- const store = load()
52
- if (!store.current) return null
53
- return store.users[store.current] || null
122
+ const { controlPlane } = load()
123
+ if (!controlPlane.current) return null
124
+ return controlPlane.profiles[controlPlane.current] || null
54
125
  }
55
126
 
56
127
  // Resolve a selector to a stored userId: an exact userId match wins, else a case-insensitive email match.
57
128
  // Throws if nothing matches, or if an email matches more than one account (disambiguate with the userId).
58
129
  function resolve(selector) {
59
130
  if (!selector) throw new Error('an account selector (email or userId) is required')
60
- const store = load()
61
- if (store.users[selector]) return selector
131
+ const { profiles } = load().controlPlane
132
+ if (profiles[selector]) return selector
62
133
  const needle = String(selector).toLowerCase()
63
- const matches = Object.values(store.users).filter((u) => (u.email || '').toLowerCase() === needle)
134
+ const matches = Object.values(profiles).filter((u) => (u.email || '').toLowerCase() === needle)
64
135
  if (matches.length === 1) return matches[0].userId
65
136
  if (matches.length > 1) throw new Error(`"${selector}" matches ${matches.length} accounts — switch by userId: ${matches.map((m) => m.userId).join(', ')}`)
66
137
  throw new Error(`no stored account for "${selector}"`)
@@ -71,28 +142,144 @@ function resolve(selector) {
71
142
  function setCurrent(selector) {
72
143
  const userId = resolve(selector)
73
144
  const store = load()
74
- store.users[userId] = { ...store.users[userId], lastUsedAt: Date.now() }
75
- store.current = userId
145
+ store.controlPlane.profiles[userId] = { ...store.controlPlane.profiles[userId], lastUsedAt: Date.now() }
146
+ store.controlPlane.current = userId
76
147
  save(store)
77
- return store.users[userId]
148
+ return store.controlPlane.profiles[userId]
78
149
  }
79
150
 
80
- // All cached accounts, most-recently-used first (accounts without a lastUsedAt sort last).
151
+ // All cached control-plane accounts, most-recently-used first (accounts without a lastUsedAt sort last).
81
152
  function list() {
82
- const store = load()
83
- return Object.values(store.users).sort((a, b) => (b.lastUsedAt || 0) - (a.lastUsedAt || 0))
153
+ return mostRecentFirst(Object.values(load().controlPlane.profiles))
84
154
  }
85
155
 
86
- // Remove one account (or the current one) and clear/repoint `current` as needed.
156
+ // Remove one control-plane account (or the current one). Removing the current account clears `current` rather than
157
+ // switching to another cached account, so no command runs as an identity the user did not choose.
87
158
  function clear(userId) {
88
159
  const store = load()
89
- const target = userId || store.current
90
- if (target && store.users[target]) delete store.users[target]
91
- if (store.current === target) {
92
- const remaining = Object.keys(store.users)
93
- store.current = remaining.length ? remaining[0] : null
160
+ const cp = store.controlPlane
161
+ const target = userId || cp.current
162
+ if (target && cp.profiles[target]) delete cp.profiles[target]
163
+ if (cp.current === target) cp.current = null
164
+ save(store)
165
+ }
166
+
167
+ // ---- deployment logins ----------------------------------------------------------------------------------------------
168
+
169
+ /**
170
+ * @template {{ lastUsedAt?: number }} T
171
+ * @param {T[]} rows
172
+ * @returns {T[]}
173
+ */
174
+ function mostRecentFirst(rows) {
175
+ return rows.sort((a, b) => (b.lastUsedAt || 0) - (a.lastUsedAt || 0))
176
+ }
177
+
178
+ /**
179
+ * @param {{ deploymentId: string, serviceInstance: string, userId: string }} p
180
+ * @returns {string}
181
+ */
182
+ function deploymentProfileKey(p) {
183
+ return `${p.deploymentId}/${p.serviceInstance}/${p.userId}`
184
+ }
185
+
186
+ /**
187
+ * Upsert a deployment login and make it the current one. Never touches control-plane logins.
188
+ * @param {Omit<DeploymentProfile, 'key'|'lastUsedAt'>} record
189
+ * @returns {DeploymentProfile}
190
+ */
191
+ function setDeploymentProfile(record) {
192
+ const key = deploymentProfileKey(record)
193
+ const store = load()
194
+ store.deployments.profiles[key] = { ...store.deployments.profiles[key], ...record, key, lastUsedAt: Date.now() }
195
+ store.deployments.current = key
196
+ save(store)
197
+ return store.deployments.profiles[key]
198
+ }
199
+
200
+ /**
201
+ * Merge fields into one stored deployment login (e.g. refreshed tokens) without changing which one is current.
202
+ * @param {string} key
203
+ * @param {Partial<DeploymentProfile>} patch
204
+ * @returns {DeploymentProfile}
205
+ */
206
+ function updateDeploymentProfile(key, patch) {
207
+ const store = load()
208
+ if (!store.deployments.profiles[key]) throw new Error(`no deployment login ${key}`)
209
+ store.deployments.profiles[key] = { ...store.deployments.profiles[key], ...patch, key }
210
+ save(store)
211
+ return store.deployments.profiles[key]
212
+ }
213
+
214
+ /** @returns {DeploymentProfile[]} most-recently-used first */
215
+ function listDeploymentProfiles() {
216
+ return mostRecentFirst(Object.values(load().deployments.profiles))
217
+ }
218
+
219
+ /** @returns {DeploymentProfile|null} */
220
+ function currentDeploymentProfile() {
221
+ const { deployments } = load()
222
+ return (deployments.current && deployments.profiles[deployments.current]) || null
223
+ }
224
+
225
+ /**
226
+ * The one deployment login a command acts as. --deployment (dep id or environment), --as (email or userId) and
227
+ * --user-service-instance narrow the stored logins; with none of them, the current login (set by `login --deployment`
228
+ * or `deployment use`). Never guesses: no match, several matches or no selection throw with the command to run.
229
+ * @param {{ deployment?: string, as?: string, 'user-service-instance'?: string }} flags
230
+ * @returns {DeploymentProfile}
231
+ */
232
+ function selectDeploymentProfile(flags) {
233
+ const selector = flags.deployment
234
+ const user = flags.as
235
+ const instance = flags['user-service-instance']
236
+ if (!selector && !user && !instance) {
237
+ const current = currentDeploymentProfile()
238
+ if (current) return current
239
+ throw new Error('no deployment login selected — run `saaslayer login --deployment <dep_id|env>` or `saaslayer deployment use <dep_id|env>`')
240
+ }
241
+ const needle = user ? String(user).toLowerCase() : null
242
+ const matches = listDeploymentProfiles().filter((p) =>
243
+ (!selector || p.deploymentId === selector || p.environment === selector)
244
+ && (!needle || p.userId === user || (p.email || '').toLowerCase() === needle)
245
+ && (!instance || p.serviceInstance === instance))
246
+ const what = [selector, user, instance && `user-service ${instance}`].filter(Boolean).join(' ')
247
+ if (matches.length === 0) throw new Error(`no deployment login for ${what} — run \`saaslayer login --deployment ${selector || '<dep_id|env>'}\``)
248
+ if (matches.length > 1) {
249
+ const rows = matches.map((p) => ` ${p.deploymentId}${p.environment ? ` (${p.environment})` : ''} user-service ${p.serviceInstance} ${p.email || p.userId}`)
250
+ throw new Error([`${matches.length} deployment logins match ${what}:`, ...rows, 'pass --deployment <dep_id>, --as <email> or --user-service-instance <name> to choose one'].join('\n'))
94
251
  }
252
+ return matches[0]
253
+ }
254
+
255
+ /**
256
+ * Make one deployment login current (see selectDeploymentProfile for the selection rules).
257
+ * @param {{ deployment?: string, as?: string, 'user-service-instance'?: string }} flags
258
+ * @returns {DeploymentProfile}
259
+ */
260
+ function useDeploymentProfile(flags) {
261
+ const profile = selectDeploymentProfile(flags)
262
+ const store = load()
263
+ store.deployments.profiles[profile.key] = { ...profile, lastUsedAt: Date.now() }
264
+ store.deployments.current = profile.key
95
265
  save(store)
266
+ return store.deployments.profiles[profile.key]
96
267
  }
97
268
 
98
- module.exports = { storeDir, storePath, load, save, setUser, getCurrent, resolve, setCurrent, list, clear }
269
+ /**
270
+ * Remove one deployment login; clears the current pointer when it was current (never repoints it).
271
+ * @param {string} key
272
+ */
273
+ function clearDeploymentProfile(key) {
274
+ const store = load()
275
+ delete store.deployments.profiles[key]
276
+ if (store.deployments.current === key) store.deployments.current = null
277
+ save(store)
278
+ }
279
+
280
+ module.exports = {
281
+ storeDir, storePath, load, save,
282
+ setUser, getCurrent, resolve, setCurrent, list, clear,
283
+ setDeploymentProfile, updateDeploymentProfile, listDeploymentProfiles, currentDeploymentProfile,
284
+ selectDeploymentProfile, useDeploymentProfile, clearDeploymentProfile,
285
+ }
@@ -0,0 +1,61 @@
1
+ // Auth headers for calls to a deployment's permissions/users API from the CLI: an IAM principal token (--iam, exchanged from
2
+ // your AWS identity), an API key (--token), or a deployment login (`saaslayer login --deployment`). Shared by commands.
3
+ 'use strict'
4
+ const creds = require('./credentials')
5
+ const { refreshIfExpired } = require('./deployment-auth')
6
+
7
+ const CHOOSE = '--iam <principalId>, --token (or $SAASLAYER_TOKEN), or a deployment login (`saaslayer login --deployment <dep_id|env>`) is required'
8
+
9
+ /**
10
+ * @param {string} token
11
+ * @returns {Record<string, string>}
12
+ */
13
+ function apiKeyHeaders(token) {
14
+ return { 'x-api-key': token, authorization: `Bearer ${token}` }
15
+ }
16
+
17
+ /**
18
+ * Refuse to send a deployment login to a host that is not one of that deployment's published API bases.
19
+ * @param {import('./credentials').DeploymentProfile} profile
20
+ * @param {string} apiBase
21
+ */
22
+ function assertServes(profile, apiBase) {
23
+ const norm = (u) => String(u || '').replace(/\/+$/, '')
24
+ if ([profile.usersApiBase, profile.permissionsApiBase].map(norm).includes(norm(apiBase))) return
25
+ throw new Error(`refusing to send the ${profile.deploymentId} deployment login to ${norm(apiBase)} — that deployment serves ${norm(profile.permissionsApiBase)} and ${norm(profile.usersApiBase)}`)
26
+ }
27
+
28
+ /**
29
+ * Request auth headers. Explicit flags win: --iam (IAM principal token as bearer), --token (api key + bearer),
30
+ * --deployment/--as/--user-service-instance (that deployment login's id token). Without one, the ambient source is
31
+ * used: $SAASLAYER_TOKEN or the current deployment login — both at once is ambiguous and refused.
32
+ * @param {string} apiBase
33
+ * @param {{ token?: string, iam?: string, region?: string, profile?: string, deployment?: string, as?: string, 'user-service-instance'?: string }} flags
34
+ * @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> }} deps
35
+ * @returns {Promise<Record<string, string>>}
36
+ */
37
+ async function authHeaders(apiBase, flags, { exchange }) {
38
+ if (flags.iam && flags.token) throw new Error('pass only one of --iam, --token or a deployment login (--deployment)')
39
+ if (flags.iam) {
40
+ const region = flags.region || process.env.AWS_REGION || 'us-west-2'
41
+ const token = await exchange({ apiBase, principalId: flags.iam, region, profile: flags.profile })
42
+ return { authorization: `Bearer ${token}` }
43
+ }
44
+ if (flags.token) return apiKeyHeaders(flags.token)
45
+ const deploymentSelected = Boolean(flags.deployment || flags.as || flags['user-service-instance'])
46
+ const envToken = process.env.SAASLAYER_TOKEN
47
+ if (!deploymentSelected) {
48
+ const current = creds.currentDeploymentProfile()
49
+ if (envToken && current) {
50
+ throw new Error(`both $SAASLAYER_TOKEN and the deployment login ${current.deploymentId} (${current.email || current.userId}) are available — pass --token, --iam or --deployment to choose`)
51
+ }
52
+ if (envToken) return apiKeyHeaders(envToken)
53
+ if (!current) throw new Error(CHOOSE)
54
+ }
55
+ const profile = creds.selectDeploymentProfile(flags)
56
+ assertServes(profile, apiBase)
57
+ const fresh = await refreshIfExpired(profile)
58
+ return { authorization: `Bearer ${fresh.idToken}` }
59
+ }
60
+
61
+ module.exports = { authHeaders }
@@ -0,0 +1,38 @@
1
+ // The id token of the selected deployment login (option B access-admin access), refreshed against that
2
+ // deployment's own pool client when expired. Never reads or changes the control-plane login.
3
+ 'use strict'
4
+ const creds = require('./credentials')
5
+ const { isFresh, refreshCognitoTokens } = require('./api-client')
6
+
7
+ /**
8
+ * @param {{ deployment?: string, as?: string, 'user-service-instance'?: string }} flags
9
+ * @returns {Promise<string>}
10
+ */
11
+ async function deploymentBearer(flags) {
12
+ return (await freshDeploymentProfile(flags)).idToken
13
+ }
14
+
15
+ /**
16
+ * The selected deployment login with a usable id token.
17
+ * @param {{ deployment?: string, as?: string, 'user-service-instance'?: string }} flags
18
+ * @returns {Promise<import('./credentials').DeploymentProfile>}
19
+ */
20
+ async function freshDeploymentProfile(flags) {
21
+ return refreshIfExpired(creds.selectDeploymentProfile(flags))
22
+ }
23
+
24
+ /**
25
+ * A deployment login with a usable id token: as stored, or refreshed with its own pool client and persisted.
26
+ * @param {import('./credentials').DeploymentProfile} profile
27
+ * @returns {Promise<import('./credentials').DeploymentProfile>}
28
+ */
29
+ async function refreshIfExpired(profile) {
30
+ if (isFresh(profile)) return profile
31
+ const relogin = `deployment login for ${profile.deploymentId} expired — run \`saaslayer login --deployment ${profile.deploymentId}\``
32
+ if (!profile.refreshToken) throw new Error(relogin)
33
+ const fresh = await refreshCognitoTokens({ region: profile.region, clientId: profile.clientId, refreshToken: profile.refreshToken })
34
+ if (!fresh) throw new Error(relogin)
35
+ return creds.updateDeploymentProfile(profile.key, { idToken: fresh.idToken, accessToken: fresh.accessToken || profile.accessToken, expiresAt: fresh.expiresAt })
36
+ }
37
+
38
+ module.exports = { deploymentBearer, freshDeploymentProfile, refreshIfExpired }
@@ -1,27 +1,26 @@
1
- // Shared deploy helpers: the active project, and resolving a deployment id for (project, env, region)
2
- // from the project-deployments view (so lifecycle commands take project+env+region, not a raw id).
1
+ // Shared deploy helpers: resolving a deployment id for (project, env, region) from the project-deployments view
2
+ // (so lifecycle commands take project+env+region, not a raw id). Prints the scope line before it reads.
3
3
  'use strict'
4
4
  const { apiCall } = require('./api-client')
5
- const context = require('./context-store')
6
-
7
- function activeProject(flags) {
8
- const p = flags.project || context.get('project')
9
- if (!p) throw new Error('no project selected — run `saaslayer project use <id>` or pass --project')
10
- return p
11
- }
5
+ const { resolveScope, printScope, deployedProjectsHint } = require('./scope')
12
6
 
13
7
  async function resolveDeployment(flags) {
14
- const project = activeProject(flags)
15
- const env = flags.env || 'prod'
8
+ const scope = resolveScope(flags, { env: 'prod' })
9
+ printScope(scope, flags)
10
+ const project = scope.project.value
11
+ const env = scope.env.value
16
12
  const region = flags.region
17
13
  const view = await apiCall('GET', `/api/projects/${encodeURIComponent(project)}/deployments`, undefined, flags)
18
14
  const group = (view.environments || []).find((g) => g.environment === env)
19
15
  let instances = group ? group.instances : []
20
16
  if (region) instances = instances.filter((i) => i.region === region)
21
- if (instances.length === 0) throw new Error(`no ${env} deployment${region ? ` in ${region}` : ''} for project ${project}`)
17
+ if (instances.length === 0) {
18
+ const hint = await deployedProjectsHint(scope, flags)
19
+ throw new Error([`no ${env} deployment${region ? ` in ${region}` : ''} for project ${project} (${scope.project.kind})`, ...hint].join('\n'))
20
+ }
22
21
  if (instances.length > 1) throw new Error(`multiple ${env} deployments — pass --region <r>: ${instances.map((i) => i.region).join(', ')}`)
23
22
  const inst = instances[0]
24
23
  return { project, env, region: inst.region, deploymentId: inst.deploymentId, status: inst.status }
25
24
  }
26
25
 
27
- module.exports = { activeProject, resolveDeployment }
26
+ module.exports = { resolveDeployment }
@@ -0,0 +1,66 @@
1
+ // Deployment discovery for CLI commands: a deployment's public configuration (pool/client ids, region, issuer, users +
2
+ // permissions API bases) from the shared @saaslayer/discovery package — monorepo source first, else the published vendor copy.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+ const path = require('path')
6
+ const { pathToFileURL } = require('url')
7
+
8
+ const MONOREPO_ENTRY = path.join(__dirname, '../../discovery/src/index.mjs')
9
+ const VENDORED_ENTRY = path.join(__dirname, '../vendor/discovery/index.mjs')
10
+
11
+ /** @returns {Promise<typeof import('../../discovery/src/index.mjs')>} */
12
+ function loadDiscovery() {
13
+ return import(pathToFileURL(fs.existsSync(MONOREPO_ENTRY) ? MONOREPO_ENTRY : VENDORED_ENTRY).href)
14
+ }
15
+
16
+ /**
17
+ * Fetch and validate a deployment's public discovery document (no credentials sent).
18
+ * @param {{ url: string } | { apiBase: string, deploymentId: string, instances?: { 'user-service'?: string, 'permissions-service'?: string } }} target
19
+ * @param {{ fetch?: typeof fetch }} [options]
20
+ */
21
+ async function discoverDeployment(target, options = {}) {
22
+ const { fetchDeploymentDiscovery } = await loadDiscovery()
23
+ return fetchDeploymentDiscovery(target, options)
24
+ }
25
+
26
+ /**
27
+ * Pick one deployment by project (slug or customer id) + environment (+ region) from `saaslayer deployments` rows.
28
+ * @template {{ deploymentId: string, customerSlug?: string|null, customerId?: string|null, environment?: string|null, region?: string|null }} T
29
+ * @param {T[]} rows
30
+ * @param {{ project: string, environment: string, region?: string }} query
31
+ * @returns {Promise<T>}
32
+ */
33
+ async function selectDeployment(rows, query) {
34
+ const discovery = await loadDiscovery()
35
+ return discovery.selectDeployment(rows, query)
36
+ }
37
+
38
+ /**
39
+ * The deployment a command names, discovered from its public outputs: --discovery-url, or --deployment <dep_id|env>
40
+ * (an environment is first resolved to the project's deployment) at the control-plane API (--config-url) with
41
+ * --user-service-instance picking a named user-service.
42
+ * @param {Record<string, any>} flags
43
+ * @param {{ discover?: typeof discoverDeployment }} [deps]
44
+ * @returns {Promise<{ doc: import('../../discovery/src/index.mjs').DeploymentDiscovery, deploymentId: string|null, environment: string|null, project: string|null }>}
45
+ */
46
+ async function discoverFromFlags(flags, { discover = discoverDeployment } = {}) {
47
+ if (flags['discovery-url']) return { doc: await discover({ url: flags['discovery-url'] }), deploymentId: null, environment: null, project: null }
48
+ const selector = flags.deployment
49
+ if (!selector || typeof selector !== 'string') throw new Error('a deployment id (dep_…) or an environment name is required (--deployment)')
50
+ const { apiBase } = require('./api-client')
51
+ const base = apiBase(flags)
52
+ let deploymentId = selector
53
+ let environment = null
54
+ let project = null
55
+ if (!/^dep_/.test(selector)) {
56
+ const resolved = await require('./deployments').resolveDeployment({ ...flags, env: selector })
57
+ deploymentId = resolved.deploymentId
58
+ environment = resolved.env
59
+ project = resolved.project
60
+ }
61
+ const instance = flags['user-service-instance']
62
+ const doc = await discover({ apiBase: base, deploymentId, ...(instance ? { instances: { 'user-service': instance } } : {}) })
63
+ return { doc, deploymentId, environment, project }
64
+ }
65
+
66
+ module.exports = { discoverDeployment, discoverFromFlags, selectDeployment, loadDiscovery, VENDORED_ENTRY }
@@ -0,0 +1,143 @@
1
+ // Environment comparison: two deployments' module revisions and settings side by side, optionally against a release
2
+ // manifest (bundle revision, permissions writer format, per-environment settings), with the gaps that keep them from matching.
3
+ 'use strict'
4
+ const { diffSettings } = require('./settings')
5
+ const { PERMISSIONS_WRITER, permissionDocFormatFor, short } = require('./release-manifest')
6
+
7
+ /**
8
+ * @typedef {import('./settings').DeploymentSettings} DeploymentSettings
9
+ * @typedef {import('./release-manifest').ReleaseManifest} ReleaseManifest
10
+ * @typedef {import('./settings').SettingsPatch} SettingsPatch
11
+ * @typedef {{ env: string, settings: DeploymentSettings }} Side
12
+ * @typedef {{ ref: string, module: string, a: string|null, b: string|null, differs: boolean }} ModuleRow
13
+ * @typedef {{ module: string, name: string, a: string, b: string, createOnly: boolean, secret: boolean }} SettingRow
14
+ * @typedef {{ code: string, env: string|null, module: string|null, setting?: string, message: string }} Gap
15
+ * @typedef {{ envs: [string, string], bundleRevision: string|null, modules: ModuleRow[], settings: SettingRow[], gaps: Gap[] }} Comparison
16
+ */
17
+
18
+ /** A module's display ref (its id for the default instance). @param {{ ref?: string, module: string }} m */
19
+ const refOf = (m) => m.ref || m.module
20
+
21
+ /**
22
+ * Compare two environments. With a manifest, each environment is also checked against the release: modules outside
23
+ * the bundle or behind its revision, bundle modules it lacks, the permission-doc format its permissions service writes, and (from
24
+ * `envPatches`, the manifest's per-environment settings) deployed values that differ. Gap messages name modules and
25
+ * settings, never values.
26
+ * @param {Side} left
27
+ * @param {Side} right
28
+ * @param {{ manifest?: ReleaseManifest|null, envPatches?: Record<string, SettingsPatch|undefined> }} [opts]
29
+ * @returns {Comparison}
30
+ */
31
+ function compareEnvironments(left, right, { manifest = null, envPatches = {} } = {}) {
32
+ const sides = [left, right]
33
+ /** @type {Gap[]} */
34
+ const gaps = []
35
+ const gap = (code, env, module, message, setting) => gaps.push({ code, env, module, ...(setting ? { setting } : {}), message })
36
+ const byRef = sides.map((s) => new Map(s.settings.modules.map((m) => [refOf(m), m])))
37
+ const refs = [...new Set(byRef.flatMap((m) => [...m.keys()]))].sort()
38
+
39
+ /** @type {ModuleRow[]} */
40
+ const modules = refs.map((ref) => {
41
+ const [a, b] = byRef.map((m) => m.get(ref))
42
+ const revision = (m) => (m ? m.revision || 'unknown' : null)
43
+ return { ref, module: (a || b).module, a: revision(a), b: revision(b), differs: revision(a) !== revision(b) }
44
+ })
45
+
46
+ const bundle = manifest ? manifest.bundle : null
47
+ for (const row of modules) {
48
+ sides.forEach((side, i) => {
49
+ const other = sides[1 - i]
50
+ const m = byRef[i].get(row.ref)
51
+ if (!m) { gap('module_only_in', side.env, row.ref, `${row.ref} is deployed in ${other.env} but not in ${side.env}`); return }
52
+ if (m.schemaError) gap('schema_unavailable', side.env, row.ref, `${row.ref} in ${side.env} has no settings schema (${m.schemaError}); its settings are not compared`)
53
+ })
54
+ if (!bundle) continue
55
+ sides.forEach((side, i) => {
56
+ const m = byRef[i].get(row.ref)
57
+ if (!m) return
58
+ if (!(m.module in bundle.modules)) gap('not_in_bundle', side.env, row.ref, `${row.ref} is deployed in ${side.env} but not in the release bundle`)
59
+ else if (m.revision !== bundle.revision) gap('behind_bundle', side.env, row.ref, `${side.env} runs ${row.ref}@${short(m.revision || '')}; the release bundle is ${short(bundle.revision)}`)
60
+ })
61
+ }
62
+
63
+ if (bundle) {
64
+ for (const module of Object.keys(bundle.modules).sort()) {
65
+ sides.forEach((side, i) => {
66
+ if (![...byRef[i].values()].some((m) => m.module === module)) gap('missing_from_env', side.env, module, `${module} is in the release bundle but not deployed in ${side.env}`)
67
+ })
68
+ }
69
+ const declared = manifest && manifest.compatibility && manifest.compatibility.permissions
70
+ if (declared && PERMISSIONS_WRITER.module in bundle.modules) {
71
+ sides.forEach((side, i) => {
72
+ const writer = [...byRef[i].values()].find((m) => m.module === PERMISSIONS_WRITER.module)
73
+ const s = writer && writer.settings.find((x) => x.name === PERMISSIONS_WRITER.permissionDocSetting)
74
+ if (!s) return
75
+ const writes = permissionDocFormatFor(s.value)
76
+ if (writes !== declared.writes.permissionDoc) {
77
+ gap('writer_format_mismatch', side.env, PERMISSIONS_WRITER.module, `${side.env} writes permissionDoc ${writes} (${PERMISSIONS_WRITER.module}.${PERMISSIONS_WRITER.permissionDocSetting}) but the release declares permissionDoc ${declared.writes.permissionDoc}`, PERMISSIONS_WRITER.permissionDocSetting)
78
+ }
79
+ })
80
+ }
81
+ }
82
+
83
+ /** @param {string} ref @param {string} name */
84
+ const settingOf = (i, ref, name) => {
85
+ const m = byRef[i].get(ref)
86
+ return m ? m.settings.find((s) => s.name === name) : undefined
87
+ }
88
+ /** @type {SettingRow[]} */
89
+ const settings = diffSettings(left.settings, right.settings).map((row) => {
90
+ const both = [settingOf(0, row.module, row.name), settingOf(1, row.module, row.name)].filter(Boolean)
91
+ return { ...row, createOnly: both.some((s) => s.updateBehavior === 'create-only'), secret: both.some((s) => s.secret) }
92
+ })
93
+ for (const row of settings) {
94
+ if (row.createOnly && row.a !== '(not deployed)' && row.b !== '(not deployed)') {
95
+ gap('create_only_differs', null, row.module, `${row.module}.${row.name} is create-only and differs: a standing deployment cannot change it, so the environments match only if one is re-created`, row.name)
96
+ }
97
+ }
98
+
99
+ sides.forEach((side, i) => {
100
+ const patch = envPatches[side.env]
101
+ if (!patch) return
102
+ for (const [ref, values] of Object.entries(patch)) {
103
+ for (const [name, value] of Object.entries(values)) {
104
+ const s = settingOf(i, ref, name)
105
+ const label = `${ref}.${name}`
106
+ if (!s) { gap('settings_drift', side.env, ref, `${label} is in the manifest's ${side.env} settings but not deployed in ${side.env}`, name); continue }
107
+ const drift = value === null
108
+ ? s.source === 'set'
109
+ : s.secret ? !s.isSet : s.value === null || s.value === undefined || String(s.value) !== String(value)
110
+ if (drift) gap('settings_drift', side.env, ref, `${label} in ${side.env} differs from the manifest's ${side.env} settings`, name)
111
+ }
112
+ }
113
+ })
114
+
115
+ return { envs: [left.env, right.env], bundleRevision: bundle ? bundle.revision : null, modules, settings, gaps }
116
+ }
117
+
118
+ /**
119
+ * Text lines for a comparison: module revisions, differing settings (create-only and secret marked), then gaps.
120
+ * @param {Comparison} c
121
+ * @returns {string[]}
122
+ */
123
+ function formatComparison(c) {
124
+ const [ea, eb] = c.envs
125
+ const width = Math.max(ea.length, eb.length) + 1
126
+ const rev = (r) => (r === null ? '(not deployed)' : r === 'unknown' ? 'unknown' : short(r))
127
+ const lines = [`modules${c.bundleRevision ? ` (release bundle ${short(c.bundleRevision)})` : ''}:`]
128
+ for (const m of c.modules) lines.push(` ${m.ref.padEnd(Math.max(...c.modules.map((x) => x.ref.length)))} ${ea}=${rev(m.a)} ${eb}=${rev(m.b)}${m.differs ? ' (differs)' : ''}`)
129
+ lines.push(c.settings.length ? 'settings that differ:' : 'settings: no differences')
130
+ for (const r of c.settings) {
131
+ const marks = [r.createOnly ? 'create-only' : null, r.secret ? 'secret' : null].filter(Boolean)
132
+ lines.push(` ${r.module}.${r.name}${marks.length ? ` [${marks.join(', ')}]` : ''}`)
133
+ lines.push(` ${`${ea}:`.padEnd(width)} ${r.a}`)
134
+ lines.push(` ${`${eb}:`.padEnd(width)} ${r.b}`)
135
+ }
136
+ if (c.gaps.length) {
137
+ lines.push('gaps:')
138
+ for (const g of c.gaps) lines.push(` ! ${g.message}`)
139
+ }
140
+ return lines
141
+ }
142
+
143
+ module.exports = { compareEnvironments, formatComparison }