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
package/src/api-client.js CHANGED
@@ -1,18 +1,25 @@
1
- // Authenticated calls to the SaaSLayer control-plane API using the cached Cognito id token (Bearer).
2
- // Shared by the org/project/aws commands.
1
+ // Authenticated calls to the SaaSLayer control-plane API using the cached control-plane Cognito id token (Bearer).
2
+ // Shared by the org/project/aws commands. Also holds the Cognito token refresh both login authorities use.
3
3
  'use strict'
4
4
  const creds = require('./credentials')
5
- const { resolvePoolConfig } = require('./config')
5
+ const { resolvePoolConfig, controlPlaneUrl } = require('./config')
6
6
 
7
7
  function apiBase(flags = {}) {
8
- const base = flags['config-url'] || process.env.SAASLAYER_CONFIG_URL
9
- if (!base) throw new Error('control-plane API base required: pass --config-url or set $SAASLAYER_CONFIG_URL')
10
- return String(base).replace(/\/$/, '')
8
+ return String(controlPlaneUrl(flags).value).replace(/\/$/, '')
11
9
  }
12
10
 
13
11
  // Refresh a little before expiry so a token never lapses mid-request.
14
12
  const REFRESH_SKEW_SECONDS = 60
15
13
 
14
+ /**
15
+ * Whether a cached token is still usable (no expiry recorded counts as usable).
16
+ * @param {{ expiresAt?: number }} profile
17
+ */
18
+ function isFresh(profile) {
19
+ const now = Math.floor(Date.now() / 1000)
20
+ return !profile.expiresAt || profile.expiresAt - REFRESH_SKEW_SECONDS > now
21
+ }
22
+
16
23
  function bearer() {
17
24
  const current = creds.getCurrent()
18
25
  if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
@@ -20,52 +27,65 @@ function bearer() {
20
27
  }
21
28
 
22
29
  /**
23
- * Exchange the stored refresh token for fresh id/access tokens (Cognito REFRESH_TOKEN_AUTH) and persist them.
24
- * The refresh token itself is not rotated by Cognito, so it is kept.
25
- * @param {object} current the cached account record
26
- * @param {object} flags
30
+ * Exchange a refresh token for fresh id/access tokens with the app client that issued it (Cognito
31
+ * REFRESH_TOKEN_AUTH). Cognito does not rotate the refresh token, so callers keep it. Returns null when refused.
32
+ * @param {{ region: string, clientId: string, refreshToken: string }} input
33
+ * @returns {Promise<{ idToken: string, accessToken?: string, expiresAt: number } | null>}
27
34
  */
28
- async function refreshTokens(current, flags) {
29
- const pool = await resolvePoolConfig(flags)
30
- const res = await fetch(`https://cognito-idp.${pool.region}.amazonaws.com/`, {
35
+ async function refreshCognitoTokens({ region, clientId, refreshToken }) {
36
+ const res = await fetch(`https://cognito-idp.${region}.amazonaws.com/`, {
31
37
  method: 'POST',
32
38
  headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'AWSCognitoIdentityProviderService.InitiateAuth' },
33
- body: JSON.stringify({ AuthFlow: 'REFRESH_TOKEN_AUTH', ClientId: pool.clientId, AuthParameters: { REFRESH_TOKEN: current.refreshToken } }),
39
+ body: JSON.stringify({ AuthFlow: 'REFRESH_TOKEN_AUTH', ClientId: clientId, AuthParameters: { REFRESH_TOKEN: refreshToken } }),
34
40
  })
35
41
  const doc = await res.json().catch(() => ({}))
36
42
  const result = doc && doc.AuthenticationResult
37
- if (!res.ok || !result || !result.IdToken) throw new Error('session expired — run `saaslayer login`')
38
- return creds.setUser({
39
- ...current,
40
- idToken: result.IdToken,
41
- accessToken: result.AccessToken || current.accessToken,
42
- expiresAt: Math.floor(Date.now() / 1000) + (Number(result.ExpiresIn) || 3600),
43
- })
43
+ if (!res.ok || !result || !result.IdToken) return null
44
+ return { idToken: result.IdToken, accessToken: result.AccessToken, expiresAt: Math.floor(Date.now() / 1000) + (Number(result.ExpiresIn) || 3600) }
45
+ }
46
+
47
+ /**
48
+ * Refresh the control-plane login with the client it is bound to (else the control plane's published pool config)
49
+ * and persist it.
50
+ * @param {object} current the cached account record
51
+ * @param {object} flags
52
+ */
53
+ async function refreshTokens(current, flags) {
54
+ const pool = current.clientId && current.region ? current : await resolvePoolConfig(flags)
55
+ const fresh = await refreshCognitoTokens({ region: pool.region, clientId: pool.clientId, refreshToken: current.refreshToken })
56
+ if (!fresh) throw new Error('session expired — run `saaslayer login`')
57
+ return creds.setUser({ ...current, idToken: fresh.idToken, accessToken: fresh.accessToken || current.accessToken, expiresAt: fresh.expiresAt })
44
58
  }
45
59
 
46
60
  /**
47
- * The current id token, refreshed first when it is expired (or about to be).
61
+ * The current control-plane id token, refreshed first when it is expired (or about to be).
48
62
  * @param {object} [flags]
49
63
  */
50
64
  async function freshBearer(flags = {}) {
51
65
  const current = creds.getCurrent()
52
66
  if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
53
- const now = Math.floor(Date.now() / 1000)
54
- if (!current.expiresAt || current.expiresAt - REFRESH_SKEW_SECONDS > now) return current.idToken
67
+ if (isFresh(current)) return current.idToken
55
68
  if (!current.refreshToken) throw new Error('session expired — run `saaslayer login`')
56
69
  return (await refreshTokens(current, flags)).idToken
57
70
  }
58
71
 
59
- async function apiCall(method, path, body, flags) {
72
+ /**
73
+ * @param {string} method
74
+ * @param {string} path
75
+ * @param {unknown} [body]
76
+ * @param {object} [flags]
77
+ * @param {{ headers?: Record<string, string> }} [opts] extra request headers (e.g. Idempotency-Key)
78
+ */
79
+ async function apiCall(method, path, body, flags, opts = {}) {
60
80
  const token = await freshBearer(flags)
61
81
  const res = await fetch(`${apiBase(flags)}${path}`, {
62
82
  method,
63
- headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
83
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}`, ...(opts.headers || {}) },
64
84
  body: body === undefined ? undefined : JSON.stringify(body),
65
85
  })
66
86
  const doc = await res.json().catch(() => ({}))
67
- if (!res.ok) throw new Error(`${method} ${path} failed (${res.status}): ${doc.error || JSON.stringify(doc)}`)
87
+ if (!res.ok) throw Object.assign(new Error(`${method} ${path} failed (${res.status}): ${doc.error || JSON.stringify(doc)}`), { status: res.status, body: doc })
68
88
  return doc
69
89
  }
70
90
 
71
- module.exports = { apiBase, bearer, freshBearer, apiCall }
91
+ module.exports = { apiBase, bearer, freshBearer, apiCall, isFresh, refreshCognitoTokens }
package/src/aws-sigv4.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // AWS Signature Version 4 request signing (no SDK dependency): signs every provided header plus x-amz-date and,
2
- // with temporary credentials, x-amz-security-token. Used to build the STS proof for the rbac IAM exchange.
2
+ // with temporary credentials, x-amz-security-token. Used to build the STS proof for the permissions IAM exchange.
3
3
  'use strict'
4
4
  const crypto = require('crypto')
5
5
 
@@ -0,0 +1,73 @@
1
+ // `saaslayer permissions access-admins list|offer|status|cancel|accept|activate`: the deployment's administrators through the permissions
2
+ // API — who counts as usable, and the transfer / add-and-verify workflow (offer → target accepts → initiator leaves).
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { permissionsRequest } = require('../permissions-request')
6
+
7
+ /**
8
+ * @typedef {import('../permissions-request').PermissionsFlags & { mode?: string, 'expires-in-hours'?: string }} AdminFlags
9
+ * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
10
+ */
11
+
12
+ /** @param {string} label @param {string[]} positional @param {string} what */
13
+ function required(label, positional, what) {
14
+ if (!positional[0]) throw new Error(`${label}: <${what}> is required`)
15
+ return positional[0]
16
+ }
17
+
18
+ /** @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
19
+ const transferOf = (body) => ({ id: body.data.id, ...body.data.attributes })
20
+
21
+ /**
22
+ * The deployment's administrators and how many count as usable humans.
23
+ * @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps]
24
+ */
25
+ async function adminsList(positional, flags, deps = {}) {
26
+ const body = await permissionsRequest('permissions access-admins list', flags, deps, 'GET', '/access-admins')
27
+ return { administrators: (body.data || []).map((/** @type {{ attributes: object }} */ d) => d.attributes), usableAdministrators: (body.meta || {}).usableAdministrators }
28
+ }
29
+
30
+ /**
31
+ * Offer your seat (--mode transfer, the default: you leave once they accept) or another seat (--mode add) to <suid>.
32
+ * They hold the role at once and count once they accept.
33
+ * @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps]
34
+ */
35
+ async function adminsOffer(positional, flags, deps = {}) {
36
+ const label = 'permissions access-admins offer'
37
+ const targetId = required(label, positional, 'suid')
38
+ const mode = flags.mode || 'transfer'
39
+ if (mode !== 'transfer' && mode !== 'add') throw new Error(`${label}: --mode must be transfer or add`)
40
+ /** @type {{ targetId: string, mode: string, expiresInHours?: number }} */
41
+ const request = { targetId, mode }
42
+ if (flags['expires-in-hours'] !== undefined) request.expiresInHours = Number(flags['expires-in-hours'])
43
+ return transferOf(await permissionsRequest(label, flags, deps, 'POST', '/access-admins/transfers', request))
44
+ }
45
+
46
+ /** @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
47
+ async function adminsStatus(positional, flags, deps = {}) {
48
+ const id = required('permissions access-admins status', positional, 'transferId')
49
+ return transferOf(await permissionsRequest('permissions access-admins status', flags, deps, 'GET', `/access-admins/transfers/${encodeURIComponent(id)}`))
50
+ }
51
+
52
+ /** Cancel a pending offer you made (its grant is revoked). @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
53
+ async function adminsCancel(positional, flags, deps = {}) {
54
+ const id = required('permissions access-admins cancel', positional, 'transferId')
55
+ return transferOf(await permissionsRequest('permissions access-admins cancel', flags, deps, 'DELETE', `/access-admins/transfers/${encodeURIComponent(id)}`))
56
+ }
57
+
58
+ /**
59
+ * Accept an offer made to you (your own deployment login, verified email); repeat to resume an interrupted accept.
60
+ * @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps]
61
+ */
62
+ async function adminsAccept(positional, flags, deps = {}) {
63
+ const transferId = required('permissions access-admins accept', positional, 'transferId')
64
+ return transferOf(await permissionsRequest('permissions access-admins accept', flags, deps, 'POST', '/me/access-admin-transfers/accept', { transferId }))
65
+ }
66
+
67
+ /** Record your own activation (your deployment login, verified email). @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
68
+ async function adminsActivate(positional, flags, deps = {}) {
69
+ const body = await permissionsRequest('permissions access-admins activate', flags, deps, 'POST', '/me/activation', {})
70
+ return body.data.attributes
71
+ }
72
+
73
+ module.exports = { adminsList, adminsOffer, adminsStatus, adminsCancel, adminsAccept, adminsActivate }
@@ -1,5 +1,5 @@
1
- // `saaslayer accounts | account list | account use <email>` — inspect and switch between the SaaSLayer
2
- // accounts cached locally, so a user with several logins can move between them without re-authenticating.
1
+ // `saaslayer accounts | account use <email> | deployment logins | deployment use <dep_id|env>` — inspect and switch the
2
+ // control-plane accounts and deployment logins cached locally, without re-authenticating. Never returns tokens.
3
3
  'use strict'
4
4
  const creds = require('../credentials')
5
5
 
@@ -22,4 +22,33 @@ function accountUse(selector) {
22
22
  return creds.setCurrent(selector)
23
23
  }
24
24
 
25
- module.exports = { accountsList, accountUse }
25
+ /**
26
+ * All cached deployment logins, most-recently-used first, flagging the current one and expired tokens.
27
+ * @returns {Array<{ deploymentId: string, environment: string|null, serviceInstance: string, email: string|null, userId: string, current: boolean, expired: boolean|null }>}
28
+ */
29
+ function deploymentLogins() {
30
+ const current = creds.currentDeploymentProfile()
31
+ const now = Math.floor(Date.now() / 1000)
32
+ return creds.listDeploymentProfiles().map((p) => ({
33
+ deploymentId: p.deploymentId,
34
+ environment: p.environment || null,
35
+ serviceInstance: p.serviceInstance,
36
+ email: p.email || null,
37
+ userId: p.userId,
38
+ current: current ? p.key === current.key : false,
39
+ expired: typeof p.expiresAt === 'number' ? p.expiresAt <= now : null,
40
+ }))
41
+ }
42
+
43
+ /**
44
+ * Make one deployment login current: --deployment (dep id or environment) plus --as / --user-service-instance when
45
+ * several logins match.
46
+ * @param {{ deployment?: string, as?: string, 'user-service-instance'?: string }} flags
47
+ */
48
+ function deploymentUse(flags) {
49
+ if (!flags.deployment && !flags.as && !flags['user-service-instance']) throw new Error('deployment use requires a <dep_id|env> (and --as <email> when several logins match)')
50
+ const p = creds.useDeploymentProfile(flags)
51
+ return { deploymentId: p.deploymentId, environment: p.environment || null, serviceInstance: p.serviceInstance, email: p.email || null }
52
+ }
53
+
54
+ module.exports = { accountsList, accountUse, deploymentLogins, deploymentUse }
@@ -0,0 +1,33 @@
1
+ // `saaslayer activity --env E`: a deployment's activity feed — every change, the customer's and any operator's, with
2
+ // actor, action, reason and operation id, newest first.
3
+ 'use strict'
4
+ const { apiCall } = require('../api-client')
5
+ const { resolveDeployment } = require('../deployments')
6
+ const { loadOperations } = require('./operations')
7
+
8
+ const MAX_LIMIT = 500
9
+
10
+ /** --limit as a number, or undefined when absent. @param {object} flags */
11
+ function limitOf(flags) {
12
+ if (flags.limit === undefined) return undefined
13
+ const n = Number(flags.limit)
14
+ if (!Number.isInteger(n) || n < 1 || n > MAX_LIMIT) throw new Error(`--limit must be a whole number from 1 to ${MAX_LIMIT}`)
15
+ return n
16
+ }
17
+
18
+ /**
19
+ * Print the deployment's activity (one line per change, or the entries with --json) and return the entries.
20
+ * @param {object} flags
21
+ */
22
+ async function activityCommand(flags) {
23
+ const limit = limitOf(flags)
24
+ const deploymentId = flags.deployment || (await resolveDeployment(flags)).deploymentId
25
+ const query = limit ? `?limit=${limit}` : ''
26
+ const doc = await apiCall('GET', `/api/deployments/${encodeURIComponent(deploymentId)}/activity${query}`, undefined, flags)
27
+ const ops = loadOperations()
28
+ const entries = ((doc && doc.data) || []).map((d) => ops.redact(d.attributes))
29
+ console.log(flags.json ? JSON.stringify(entries, null, 2) : loadOperations('activity').formatActivity(entries).join('\n'))
30
+ return entries
31
+ }
32
+
33
+ module.exports = { activityCommand }
@@ -1,14 +1,15 @@
1
- // `saaslayer catalog apply|get|export` and `saaslayer rbac register`: apply a product's role catalog (PUT
2
- // /catalog/:product), register a service under its product, and export the published registry snapshot.
1
+ // `saaslayer permissions model apply|get|export`, `saaslayer permissions owner bootstrap|reconcile` and `saaslayer permissions
2
+ // register`: apply a product's role catalog (PUT /catalog/:product), bootstrap or reconcile its org owners, register a
3
+ // service under its product, and export the published registry snapshot.
3
4
  'use strict'
4
5
  const fs = require('fs')
5
6
  const path = require('path')
6
7
  const { exchangeIamToken } = require('../iam-session')
7
- const { authHeaders } = require('../rbac-auth')
8
+ const { authHeaders } = require('../deployment-api-auth')
8
9
 
9
10
  /**
10
11
  * @typedef {{ type: 'string' | 'number' | 'boolean' | 'string[]' | 'principalRef' | 'ip', required: boolean, nullable?: boolean, pii?: boolean }} AttributeSchema
11
- * @typedef {{ product: string, catalogVersion: number,
12
+ * @typedef {{ product: string, service?: string, catalogVersion: number,
12
13
  * resources: Record<string, { actions: string[], attributes?: Record<string, AttributeSchema> }>,
13
14
  * trustedContext?: boolean, contextSchema?: Record<string, AttributeSchema>,
14
15
  * roles: object[], delegation?: object, selfCheck?: object[] }} CatalogManifest
@@ -86,9 +87,9 @@ function registryLine(registry) {
86
87
  */
87
88
  async function catalogApply(positional, flags, deps = {}) {
88
89
  const manifestPath = positional[0]
89
- if (!manifestPath) throw new Error('catalog apply: a manifest path is required')
90
+ if (!manifestPath) throw new Error('permissions model apply: a manifest path is required')
90
91
  const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
91
- if (!apiBase) throw new Error('catalog apply: --api-base (or $SAASLAYER_API_BASE) is required')
92
+ if (!apiBase) throw new Error('permissions model apply: --api-base (or $SAASLAYER_API_BASE) is required')
92
93
  const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
93
94
  /** @type {CatalogManifest} */
94
95
  const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
@@ -105,12 +106,12 @@ async function catalogApply(positional, flags, deps = {}) {
105
106
  })
106
107
  const body = await res.json().catch(() => ({}))
107
108
  if (!res.ok) {
108
- throw new Error(`catalog apply failed (${res.status}): ${apiErrorDetail(body)}`)
109
+ throw new Error(`permissions model apply failed (${res.status}): ${apiErrorDetail(body)}`)
109
110
  }
110
111
  const a = body.data.attributes
111
112
  const summary = formatApplyResult(a)
112
113
  console.log(summary)
113
- if (a.plan === 'apply' && !a.dryRun && a.verified !== true) throw new Error('catalog apply: roles were written but not verified on read-back')
114
+ if (a.plan === 'apply' && !a.dryRun && a.verified !== true) throw new Error('permissions model apply: roles were written but not verified on read-back')
114
115
  return summary
115
116
  }
116
117
 
@@ -135,12 +136,12 @@ async function callCatalog(label, url, init) {
135
136
  */
136
137
  async function catalogBootstrapOwner(positional, flags, deps = {}) {
137
138
  const product = positional[0]
138
- if (!product) throw new Error('catalog bootstrap-owner: a product is required')
139
- if (!flags.org || !flags.user) throw new Error('catalog bootstrap-owner: --org and --user are required')
139
+ if (!product) throw new Error('permissions owner bootstrap: a product is required')
140
+ if (!flags.org || !flags.user) throw new Error('permissions owner bootstrap: --org and --user are required')
140
141
  const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
141
- if (!apiBase) throw new Error('catalog bootstrap-owner: --api-base (or $SAASLAYER_API_BASE) is required')
142
+ if (!apiBase) throw new Error('permissions owner bootstrap: --api-base (or $SAASLAYER_API_BASE) is required')
142
143
  const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
143
- return callCatalog('catalog bootstrap-owner', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/bootstrap-owner`, {
144
+ return callCatalog('permissions owner bootstrap', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/bootstrap-owner`, {
144
145
  method: 'POST',
145
146
  headers: { ...auth, 'content-type': 'application/json' },
146
147
  body: JSON.stringify({ orgId: flags.org, userId: flags.user }),
@@ -155,15 +156,15 @@ async function catalogBootstrapOwner(positional, flags, deps = {}) {
155
156
  */
156
157
  async function catalogReconcileOwners(positional, flags, deps = {}) {
157
158
  const product = positional[0]
158
- if (!product) throw new Error('catalog reconcile-owners: a product is required')
159
+ if (!product) throw new Error('permissions owner reconcile: a product is required')
159
160
  const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
160
- if (!apiBase) throw new Error('catalog reconcile-owners: --api-base (or $SAASLAYER_API_BASE) is required')
161
+ if (!apiBase) throw new Error('permissions owner reconcile: --api-base (or $SAASLAYER_API_BASE) is required')
161
162
  const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
162
163
  const query = new URLSearchParams()
163
164
  if (flags.apply) query.set('apply', 'true')
164
165
  if (flags.org) query.set('orgId', flags.org)
165
166
  const qs = query.toString()
166
- return callCatalog('catalog reconcile-owners', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/reconcile-owners${qs ? `?${qs}` : ''}`, {
167
+ return callCatalog('permissions owner reconcile', `${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}/reconcile-owners${qs ? `?${qs}` : ''}`, {
167
168
  method: 'POST',
168
169
  headers: { ...auth, 'content-type': 'application/json' },
169
170
  })
@@ -178,35 +179,35 @@ async function catalogReconcileOwners(positional, flags, deps = {}) {
178
179
  */
179
180
  async function catalogGet(positional, flags, deps = {}) {
180
181
  const product = positional[0]
181
- if (!product) throw new Error('catalog get: a product is required')
182
+ if (!product) throw new Error('permissions model get: a product is required')
182
183
  const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
183
- if (!apiBase) throw new Error('catalog get: --api-base (or $SAASLAYER_API_BASE) is required')
184
+ if (!apiBase) throw new Error('permissions model get: --api-base (or $SAASLAYER_API_BASE) is required')
184
185
  const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
185
186
  const res = await fetch(`${apiBase.replace(/\/$/, '')}/catalog/${encodeURIComponent(product)}`, { method: 'GET', headers: auth })
186
187
  const body = await res.json().catch(() => ({}))
187
188
  if (!res.ok) {
188
189
  const detail = (body.errors || []).map((e) => e.message || e.detail).filter(Boolean).join('; ') || JSON.stringify(body)
189
- throw new Error(`catalog get failed (${res.status}): ${detail}`)
190
+ throw new Error(`permissions model get failed (${res.status}): ${detail}`)
190
191
  }
191
192
  return body.data.attributes
192
193
  }
193
194
 
194
195
  /**
195
- * Register (upsert) a service's rbac.manifest.json under its product (POST /catalog/register). A service belongs to
196
+ * Register (upsert) a service's permissions manifest under its product (POST /catalog/register). A service belongs to
196
197
  * exactly one product: --product (or the manifest's `product`) is required.
197
198
  * @param {string[]} positional [manifestPath]
198
199
  * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, product?: string }} flags
199
200
  * @param {{ exchange?: typeof exchangeIamToken }} [deps]
200
201
  * @returns {Promise<string>} the printed summary
201
202
  */
202
- async function rbacRegister(positional, flags, deps = {}) {
203
+ async function permissionsRegister(positional, flags, deps = {}) {
203
204
  const manifestPath = positional[0]
204
- if (!manifestPath) throw new Error('rbac register: a manifest path is required')
205
+ if (!manifestPath) throw new Error('permissions register: a manifest path is required')
205
206
  const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
206
- if (!apiBase) throw new Error('rbac register: --api-base (or $SAASLAYER_API_BASE) is required')
207
+ if (!apiBase) throw new Error('permissions register: --api-base (or $SAASLAYER_API_BASE) is required')
207
208
  const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
208
209
  const product = flags.product || manifest.product
209
- if (!product) throw new Error('rbac register: --product is required (the product that owns this service)')
210
+ if (!product) throw new Error('permissions register: --product is required (the product that owns this service)')
210
211
  const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
211
212
  const a = await callCatalog('register', `${apiBase.replace(/\/$/, '')}/catalog/register`, {
212
213
  method: 'POST',
@@ -222,7 +223,7 @@ async function rbacRegister(positional, flags, deps = {}) {
222
223
  }
223
224
 
224
225
  /**
225
- * Write the currently published registry snapshot ({ meta, snapshot }) to a file — the pinned registry rbac-node
226
+ * Write the currently published registry snapshot ({ meta, snapshot }) to a file — the pinned registry @saaslayer/permissions
226
227
  * direct mode loads (GET /catalog/registry/snapshot).
227
228
  * @param {string[]} positional unused
228
229
  * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, snapshot?: boolean, out?: string }} flags
@@ -230,16 +231,16 @@ async function rbacRegister(positional, flags, deps = {}) {
230
231
  * @returns {Promise<string>} the written path
231
232
  */
232
233
  async function catalogExport(positional, flags, deps = {}) {
233
- if (!flags.snapshot) throw new Error('catalog export: --snapshot is required (the only export format)')
234
- if (!flags.out || flags.out === true) throw new Error('catalog export: --out <file> is required')
234
+ if (!flags.snapshot) throw new Error('permissions model export: --snapshot is required (the only export format)')
235
+ if (!flags.out || flags.out === true) throw new Error('permissions model export: --out <file> is required')
235
236
  const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
236
- if (!apiBase) throw new Error('catalog export: --api-base (or $SAASLAYER_API_BASE) is required')
237
+ if (!apiBase) throw new Error('permissions model export: --api-base (or $SAASLAYER_API_BASE) is required')
237
238
  const auth = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
238
- const a = await callCatalog('catalog export', `${apiBase.replace(/\/$/, '')}/catalog/registry/snapshot`, { method: 'GET', headers: auth })
239
+ const a = await callCatalog('permissions model export', `${apiBase.replace(/\/$/, '')}/catalog/registry/snapshot`, { method: 'GET', headers: auth })
239
240
  const outPath = path.resolve(String(flags.out))
240
241
  fs.writeFileSync(outPath, `${JSON.stringify({ meta: a.meta, snapshot: a.snapshot }, null, 2)}\n`)
241
242
  console.log(`wrote registry snapshot v${a.snapshot && a.snapshot.version} to ${outPath}`)
242
243
  return outPath
243
244
  }
244
245
 
245
- module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport, rbacRegister, formatApplyResult }
246
+ module.exports = { catalogApply, catalogGet, catalogBootstrapOwner, catalogReconcileOwners, catalogExport, permissionsRegister, formatApplyResult }
@@ -0,0 +1,64 @@
1
+ // `saaslayer context` — what the CLI will act as and on: the control-plane account, the deployment login, the AWS
2
+ // profile, the control-plane URL, the org and project (with where each came from) and every cached identity. No tokens.
3
+ 'use strict'
4
+ const context = require('../context-store')
5
+ const { projectIdKind } = require('../scope')
6
+ const { accountsList, deploymentLogins } = require('./accounts')
7
+ const { controlPlaneUrl } = require('../config')
8
+
9
+ /**
10
+ * @param {object} flags
11
+ */
12
+ function contextShow(flags) {
13
+ const current = accountsList().find((a) => a.current)
14
+ const org = context.get('org')
15
+ const project = context.get('project')
16
+ const logins = deploymentLogins()
17
+ const deployment = logins.find((d) => d.current) || null
18
+ const awsEnv = process.env.AWS_PROFILE
19
+ return {
20
+ account: current ? { email: current.email, userId: current.userId, controlPlane: current.env } : null,
21
+ controlPlaneUrl: controlPlaneUrl(flags),
22
+ org: org ? { value: org, source: 'context' } : { value: null, source: null },
23
+ project: project ? { value: project, source: 'context', kind: projectIdKind(project) } : { value: null, source: null, kind: null },
24
+ deployment,
25
+ awsProfile: flags.profile ? { value: flags.profile, source: 'flag' } : awsEnv ? { value: awsEnv, source: 'env' } : { value: null, source: null },
26
+ deploymentLogins: logins,
27
+ identities: accountsList().map((a) => ({ email: a.email, userId: a.userId, controlPlane: a.env, current: a.current, expired: a.expired })),
28
+ }
29
+ }
30
+
31
+ /**
32
+ * @param {ReturnType<typeof contextShow>} ctx
33
+ * @returns {string[]}
34
+ */
35
+ function formatContext(ctx) {
36
+ const lines = [
37
+ ctx.account ? `account: ${ctx.account.email} (${ctx.account.userId}) control plane: ${ctx.account.controlPlane}` : 'account: — (run `saaslayer login`)',
38
+ `control plane url: ${ctx.controlPlaneUrl.value} (from ${ctx.controlPlaneUrl.source})`,
39
+ ctx.org.value ? `org: ${ctx.org.value} (from context)` : 'org: — (run `saaslayer org use <id>`)',
40
+ ctx.project.value ? `project: ${ctx.project.value} (${ctx.project.kind}, from context)` : 'project: — (run `saaslayer project use <id>`)',
41
+ ctx.deployment ? `deployment login: ${deploymentLabel(ctx.deployment)}` : 'deployment login: — (run `saaslayer login --deployment <dep_id|env>`)',
42
+ ctx.awsProfile.value ? `aws profile: ${ctx.awsProfile.value} (from ${ctx.awsProfile.source})` : 'aws profile: — (ambient AWS credentials)',
43
+ 'cached identities:',
44
+ ]
45
+ if (!ctx.identities.length) lines.push(' none — run `saaslayer login`')
46
+ for (const i of ctx.identities) {
47
+ lines.push(`${i.current ? '*' : ' '} ${i.email} [control plane: ${i.controlPlane}]${i.expired === true ? ' (token expired)' : ''}`)
48
+ }
49
+ for (const d of ctx.deploymentLogins) {
50
+ lines.push(`${d.current ? '*' : ' '} ${deploymentLabel(d)}${d.expired === true ? ' (token expired)' : ''}`)
51
+ }
52
+ lines.push('--project/--org/--env on a command override this context for that command; --deployment/--as pick a deployment login; --profile picks the AWS profile.')
53
+ return lines
54
+ }
55
+
56
+ /**
57
+ * @param {{ deploymentId: string, environment: string|null, serviceInstance: string, email: string|null, userId: string }} d
58
+ * @returns {string}
59
+ */
60
+ function deploymentLabel(d) {
61
+ return `${d.deploymentId}${d.environment ? ` [${d.environment}]` : ''} (user-service ${d.serviceInstance}) as ${d.email || d.userId}`
62
+ }
63
+
64
+ module.exports = { contextShow, formatContext }
@@ -1,20 +1,80 @@
1
1
  // `saaslayer deploy` (swf2.7) — self-serve deploy of the customer's project into their connected account.
2
2
  // POSTs to the BFF (Bearer id token); the BFF authorizes the caller, resolves the target, and calls the
3
3
  // deployer. Handles the two-step cost-confirm (D14): the first call returns NEEDS_CONFIRMATION with an
4
- // estimate; on y (or --yes) we re-send confirmCost:true.
4
+ // estimate; on y (or --yes) we re-send confirmCost:true. Then waits for the deploy operation unless --no-wait.
5
5
  'use strict'
6
- const context = require('../context-store')
6
+ const { resolveScope, printScope } = require('../scope')
7
7
  const { apiCall } = require('../api-client')
8
8
  const { confirm } = require('../prompt')
9
+ const { finishMutation } = require('./operations')
10
+ const { fetchModuleCatalog, checkModuleIds, checkDependencies, checkParamModules } = require('../module-catalog')
11
+ const { parseSetFlags, readSettingsFile, mergePatches, checkPatch } = require('../settings')
12
+ const { fetchSchema } = require('./settings')
9
13
 
10
- async function deploy(flags) {
11
- const project = flags.project || context.get('project')
12
- if (!project) throw new Error('no project selected — run `saaslayer project use <id>` or pass --project')
13
- const environment = flags.env || 'prod'
14
- const services = flags.services ? String(flags.services).split(',').map((s) => s.trim()).filter(Boolean) : undefined
14
+ /**
15
+ * Module ids from --services a,b and --module (repeatable, comma-separated).
16
+ * @param {object} flags
17
+ * @returns {string[]|undefined}
18
+ */
19
+ function selectedModules(flags) {
20
+ const raw = [flags.services, flags.module].flat().filter((v) => typeof v === 'string')
21
+ const ids = [...new Set(raw.flatMap((v) => v.split(',')).map((s) => s.trim()).filter(Boolean))]
22
+ return ids.length ? ids : undefined
23
+ }
24
+
25
+ /**
26
+ * Check create settings against each module's schema at the revision being deployed (--commit-sha, else the default
27
+ * release the catalog reports) and name the create-only ones. With no known revision the control plane checks them.
28
+ * @param {Record<string, Record<string, unknown>>} parameters
29
+ * @param {string|undefined} commitSha
30
+ * @param {import('../module-catalog').CatalogModule[]} modules
31
+ * @param {object} flags
32
+ */
33
+ async function checkCreateSettings(parameters, commitSha, modules, flags) {
34
+ /** @param {string} id */
35
+ const revisionOf = (id) => commitSha || (modules.find((m) => m.id === id) || { attributes: {} }).attributes.revision
36
+ const ids = Object.keys(parameters)
37
+ if (ids.some((id) => !revisionOf(id))) {
38
+ console.log(' the control plane reports no default release, so settings are checked by the control plane only (pass --commit-sha to check them here first)')
39
+ return parameters
40
+ }
41
+ const schemas = Object.fromEntries(await Promise.all(ids.map(async (id) => [id, await fetchSchema(id, String(revisionOf(id)), flags)])))
42
+ const { patch, createOnly } = checkPatch(parameters, schemas, { op: 'create' })
43
+ if (createOnly.length) console.log(` create-only (fixed once deployed): ${createOnly.join(', ')}`)
44
+ return patch
45
+ }
46
+
47
+ /**
48
+ * @param {Record<string, any>} flags
49
+ * @param {{ interactive?: boolean, confirm?: (question: string) => Promise<boolean> }} [io] test seams: whether a person can
50
+ * answer (default: stdin is a terminal) and how they are asked
51
+ */
52
+ async function deploy(flags, io = {}) {
53
+ const interactive = io.interactive === undefined ? Boolean(process.stdin.isTTY) : io.interactive
54
+ const ask = io.confirm || confirm
55
+ const yes = flags.yes === true || flags.yes === 'true'
56
+ const scope = resolveScope(flags, { env: 'prod' })
57
+ printScope(scope, flags)
58
+ const project = scope.project.value
59
+ const environment = scope.env.value
60
+ const services = selectedModules(flags)
15
61
  // Accept the documented kebab flag (--commit-sha) as well as the camelCase form; parseArgs keys by the
16
62
  // literal flag, so --commit-sha lands in flags['commit-sha'].
17
63
  const commitSha = flags['commit-sha'] || flags.commitSha
64
+ // A settings file is input to this deploy; --set / --param values override it.
65
+ let parameters = mergePatches(typeof flags.settings === 'string' ? readSettingsFile(flags.settings) : undefined, parseSetFlags(flags.param, '--param'), parseSetFlags(flags.set, '--set'))
66
+ // Module ids, dependencies and --param module keys are checked against the catalog before anything is sent.
67
+ if (services || parameters) {
68
+ const modules = await fetchModuleCatalog(flags)
69
+ if (services) {
70
+ checkModuleIds(services, modules)
71
+ checkDependencies(services, modules)
72
+ }
73
+ if (parameters) {
74
+ checkParamModules(parameters, modules)
75
+ parameters = await checkCreateSettings(parameters, commitSha, modules, flags)
76
+ }
77
+ }
18
78
 
19
79
  const attributes = {
20
80
  customerId: project,
@@ -24,9 +84,16 @@ async function deploy(flags) {
24
84
  ...(flags.target ? { targetAccountId: flags.target } : {}),
25
85
  ...(commitSha ? { commitSha } : {}),
26
86
  ...(flags['admin-email'] ? { adminEmail: flags['admin-email'] } : {}),
87
+ ...(parameters ? { parameters } : {}),
27
88
  }
28
89
 
29
- console.log(`Deploying ${services ? services.join(' + ') : 'the default services'} to ${project}/${environment}${flags.region ? '/' + flags.region : ''}…`)
90
+ // Creating a deployment is never implicit: --yes, or a person confirms before the first create request is sent.
91
+ const what = `${services ? services.join(' + ') : 'the default services'} to ${project}/${environment}${flags.region ? '/' + flags.region : ''}`
92
+ if (!yes) {
93
+ if (!interactive) throw new Error(`deploy creates a deployment (${what}); pass --yes to confirm when running non-interactively`)
94
+ if (!(await ask(`Create a deployment: ${what}${flags.target ? ` in account ${flags.target}` : ''}?`))) { console.log('Aborted.'); return null }
95
+ }
96
+ console.log(`Deploying ${what}…`)
30
97
  let res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes }, }, flags)
31
98
 
32
99
  // Cost-confirm (D14): the BFF returns a deployment-estimate with status NEEDS_CONFIRMATION.
@@ -34,7 +101,7 @@ async function deploy(flags) {
34
101
  const est = res.data.attributes.estimate || {}
35
102
  const monthly = est.monthlyUsd != null ? `$${est.monthlyUsd}/mo` : 'an unknown monthly cost'
36
103
  console.log(` Estimated cost: ${monthly}.`)
37
- const ok = flags.yes === true || flags.yes === 'true' || (await confirm('Proceed with the deploy?'))
104
+ const ok = yes || (interactive && (await ask('Proceed with the deploy?')))
38
105
  if (!ok) { console.log('Aborted.'); return null }
39
106
  res = await apiCall('POST', '/api/deployments', { data: { type: 'deployments', attributes: { ...attributes, confirmCost: true } } }, flags)
40
107
  }
@@ -42,7 +109,9 @@ async function deploy(flags) {
42
109
  const dep = res.data || {}
43
110
  const run = dep.attributes && dep.attributes.run
44
111
  console.log(`✅ deploy started: deployment ${dep.id}${run && run.runId ? ` (run ${run.runId})` : ''}`)
45
- console.log(` watch: saaslayer status --project ${project}${flags.region ? ' --region ' + flags.region : ''}`)
112
+ console.log(` status: saaslayer status --project ${project}${flags.region ? ' --region ' + flags.region : ''}`)
113
+ await finishMutation({ response: res, deploymentId: dep.id, flags })
114
+ if (res.operation) dep.operation = res.operation
46
115
  return dep
47
116
  }
48
117