saaslayer 0.0.1 → 0.0.7

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.
@@ -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 }
@@ -0,0 +1,56 @@
1
+ // `saaslayer org …` and `saaslayer project …` — create/list orgs and projects against the SaaSLayer
2
+ // control-plane API, authenticated with the cached Cognito id token (Bearer). The active org is
3
+ // remembered locally so `project create` doesn't need --org each time.
4
+ 'use strict'
5
+ const context = require('../context-store')
6
+ const { apiCall } = require('../api-client')
7
+
8
+ async function orgCreate(flags, name) {
9
+ if (!name) throw new Error('org create requires a name')
10
+ const org = await apiCall('POST', '/api/orgs', { name }, flags)
11
+ context.set('org', org.id)
12
+ return org
13
+ }
14
+
15
+ async function orgList(flags) {
16
+ const doc = await apiCall('GET', '/api/orgs', undefined, flags)
17
+ return doc.orgs || []
18
+ }
19
+
20
+ function orgUse(_flags, orgId) {
21
+ if (!orgId) throw new Error('org use requires an org id')
22
+ context.set('org', orgId)
23
+ return orgId
24
+ }
25
+
26
+ // Derive an API-valid deploy slug from a name: letter-first, lowercase alnum + single hyphens, <=15 chars.
27
+ function slugify(name) {
28
+ const s = String(name).toLowerCase()
29
+ .replace(/[^a-z0-9]+/g, '-') // non-alnum -> hyphen
30
+ .replace(/-+/g, '-') // collapse hyphens
31
+ .replace(/^-+|-+$/g, '') // trim hyphens
32
+ .replace(/^[^a-z]+/, '') // enforce letter-first
33
+ .slice(0, 15)
34
+ .replace(/-+$/, '') // no trailing hyphen after truncation
35
+ return s
36
+ }
37
+
38
+ async function projectCreate(flags, name) {
39
+ if (!name) throw new Error('project create requires a name')
40
+ const orgId = flags.org || context.get('org')
41
+ if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
42
+ const slug = flags.slug || slugify(name)
43
+ if (!slug) throw new Error('project create requires a slug (letter-first, lowercase, <=15 chars) — pass --slug')
44
+ const project = await apiCall('POST', '/api/projects', { name, orgId, slug }, flags)
45
+ context.set('project', project.id)
46
+ return project
47
+ }
48
+
49
+ async function projectList(flags) {
50
+ const orgId = flags.org || context.get('org')
51
+ if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
52
+ const doc = await apiCall('GET', `/api/projects?orgId=${encodeURIComponent(orgId)}`, undefined, flags)
53
+ return doc.projects || []
54
+ }
55
+
56
+ module.exports = { orgCreate, orgList, orgUse, projectCreate, projectList }
@@ -0,0 +1,228 @@
1
+ // `saaslayer rbac inspect <type>:<id> | session:<id>`: a principal's permissions from the terminal (expanded view with
2
+ // independent scope/assignment paging, or the stored inspection model) — never parses the compact stored schema.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { authHeaders } = require('../rbac-auth')
6
+
7
+ const USAGE = '<principalType>:<id> or session:<id> (e.g. USER:alice, SERVICE_ACCOUNT:svc-1)'
8
+
9
+ /**
10
+ * @typedef {{ kind: 'principal', type: string, id: string } | { kind: 'session', id: string }} InspectRef
11
+ * @typedef {{ action: string, resource: string, service?: string, roleId?: string, policyId?: string, when?: object, expiresAt?: string }} Entry
12
+ * @typedef {{ allows: Entry[], denies: Entry[] }} Bucket
13
+ * @typedef {{ roleId: string, scope: string|null, isDirect?: boolean, isDerived?: boolean, inheritedFrom?: string|null, expiresAt?: string }} Assignment
14
+ */
15
+
16
+ /**
17
+ * @param {string|undefined} raw
18
+ * @returns {InspectRef}
19
+ */
20
+ function parseRef(raw) {
21
+ const s = typeof raw === 'string' ? raw : ''
22
+ const at = s.indexOf(':')
23
+ const type = at > 0 ? s.slice(0, at) : ''
24
+ const id = at > 0 ? s.slice(at + 1) : ''
25
+ if (!type || !id) throw new Error(`rbac inspect: expected ${USAGE}`)
26
+ if (type.toLowerCase() === 'session') return { kind: 'session', id }
27
+ return { kind: 'principal', type: type.toUpperCase(), id }
28
+ }
29
+
30
+ /** @param {number} n */
31
+ const bytes = (n) => `${Number(n || 0).toLocaleString('en-US')} B`
32
+
33
+ /**
34
+ * One line of size stats from the inspection model.
35
+ * @param {Record<string, any>|null} inspection
36
+ */
37
+ function formatSize(inspection) {
38
+ if (!inspection) return 'size (no stored doc)'
39
+ const { size, counts } = inspection
40
+ const parts = [
41
+ `main ${bytes(size.itemSizeBytes)} (${size.percentOfGate}% of the ${bytes(size.gateBytes)} gate)`,
42
+ `overflow ${bytes(size.overflowItemSizeBytes)}`,
43
+ ]
44
+ if (inspection.defCount !== undefined) parts.push(`defs ${inspection.defCount}`, `ref sets ${inspection.refSetCount || 0}`)
45
+ if (counts) parts.push(`scopes ${counts.scopeCount}`)
46
+ return `size ${parts.join(' ')}`
47
+ }
48
+
49
+ /** @param {Assignment} a */
50
+ function assignmentKind(a) {
51
+ if (a.isDerived) return 'derived'
52
+ if (a.isDirect === false) return a.inheritedFrom ? `inherited from ${a.inheritedFrom}` : 'inherited'
53
+ return 'direct'
54
+ }
55
+
56
+ /**
57
+ * Left-aligned columns.
58
+ * @param {string[][]} rows
59
+ */
60
+ function table(rows) {
61
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((r) => r[i].length)))
62
+ return rows.map((r) => ` ${r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(widths[i]))).join(' ')}`.trimEnd()).join('\n')
63
+ }
64
+
65
+ /**
66
+ * @param {'allow'|'deny'} effect
67
+ * @param {Entry} e
68
+ */
69
+ function entryLine(effect, e) {
70
+ const parts = [effect === 'allow' ? 'allow' : 'deny ', e.action, e.resource, e.service === undefined ? '(no service)' : e.service]
71
+ if (e.roleId) parts.push(`role ${e.roleId}`)
72
+ if (e.policyId) parts.push(`policy ${e.policyId}`)
73
+ if (e.when) parts.push(`when ${JSON.stringify(e.when)}`)
74
+ if (e.expiresAt) parts.push(`expires ${e.expiresAt}`)
75
+ return ` ${parts.join(' ')}`
76
+ }
77
+
78
+ /** @param {string} title @param {Bucket} bucket */
79
+ function bucketBlock(title, bucket) {
80
+ const lines = [...(bucket.allows || []).map((e) => entryLine('allow', e)), ...(bucket.denies || []).map((e) => entryLine('deny', e))]
81
+ return [title, ...(lines.length ? lines : [' (empty)'])].join('\n')
82
+ }
83
+
84
+ /**
85
+ * The expanded view as text: header + size, assignments page, global, the scope page, next-page commands.
86
+ * @param {Record<string, any>} view GET /principals/:type/:id/permissions attributes
87
+ * @param {{ ref: string, inspection: Record<string, any>|null }} opts
88
+ */
89
+ function formatExpanded(view, { ref, inspection }) {
90
+ const meta = view.meta || {}
91
+ const label = inspection ? inspection.label : `schemaVersion ${meta.schemaVersion ?? '-'}`
92
+ const out = [
93
+ `${ref} doc v${view.version || 0} ${label}${view.status === 'not_materialized' ? ' (not materialized)' : ''}`,
94
+ formatSize(inspection),
95
+ '',
96
+ `Assignments (${(view.roles || []).length} of ${meta.assignmentCount ?? (view.roles || []).length})`,
97
+ ]
98
+ const roles = /** @type {Assignment[]} */ (view.roles || [])
99
+ if (roles.length) out.push(table([['ROLE', 'SCOPE', 'KIND', 'EXPIRES'], ...roles.map((a) => [a.roleId, a.scope || 'global', assignmentKind(a), a.expiresAt || '-'])]))
100
+ else out.push(' (none)')
101
+ out.push('', bucketBlock('Global', view.global || { allows: [], denies: [] }))
102
+ const scopes = Object.keys(view.scoped || {})
103
+ out.push('')
104
+ if (scopes.length) for (const scope of scopes) out.push(bucketBlock(`Scope ${scope}`, view.scoped[scope]))
105
+ else out.push('(no scopes on this page)')
106
+ const hints = []
107
+ if (meta.nextScopeCursor) hints.push(`more scopes: saaslayer rbac inspect ${ref} --scope-page ${meta.nextScopeCursor}`)
108
+ if (meta.nextAssignmentCursor) hints.push(`more assignments: saaslayer rbac inspect ${ref} --assignment-page ${meta.nextAssignmentCursor}`)
109
+ if (hints.length) out.push('', ...hints)
110
+ return out.join('\n')
111
+ }
112
+
113
+ /**
114
+ * The stored inspection model as text (principal or session doc).
115
+ * @param {Record<string, any>} inspection
116
+ * @param {{ ref: string, session?: { sessionId: string, sessionKind: string, ceilingMode: string|null, status: string, expiresAt: string } }} opts
117
+ */
118
+ function formatInspection(inspection, { ref, session }) {
119
+ const out = [`${ref} ${inspection.label} ${inspection.docKind} doc`]
120
+ if (session) out.push(`session ${session.sessionId} ${session.sessionKind} ceiling ${session.ceilingMode || 'none'} ${session.status} expires ${session.expiresAt}`)
121
+ out.push(formatSize(inspection))
122
+ const c = inspection.counts
123
+ if (c) out.push(`counts allows ${c.allowCount} denies ${c.denyCount} scopes ${c.scopeCount} assignments ${c.assignmentCount}`)
124
+ if (inspection.overflow && inspection.overflow.present) out.push(`overflow item ${inspection.overflow.scopeCount} scopes`)
125
+ if (Array.isArray(inspection.defs) && inspection.defs.length) {
126
+ out.push('', table([['DEF', 'SOURCE', 'SERVICE', 'ALLOWS', 'DENIES', 'REFS'], ...inspection.defs.map((/** @type {any} */ d) => [d.id, String(d.src), d.svc || '-', String(d.allowCount), String(d.denyCount), `${d.refCount}${d.unused ? ' (unused)' : ''}`])]))
127
+ }
128
+ if (Array.isArray(inspection.buckets) && inspection.buckets.length) {
129
+ out.push('', table([['SCOPE', 'ALLOWS', 'DENIES'], ...inspection.buckets.map((/** @type {any} */ b) => [b.scope, String(b.allowCount), String(b.denyCount)])]))
130
+ }
131
+ const problems = inspection.problems || []
132
+ if (problems.length) out.push('', `PROBLEMS (${problems.length})`, ...problems.map((/** @type {any} */ p) => ` ${p.reason} at ${p.path}`))
133
+ else out.push('problems none')
134
+ return out.join('\n')
135
+ }
136
+
137
+ /**
138
+ * GET a JSON:API resource; errors carry a clear message per status.
139
+ * @param {string} url @param {Record<string, string>} headers @param {string} ref
140
+ * @returns {Promise<Record<string, any>>} data.attributes
141
+ */
142
+ async function getAttributes(url, headers, ref) {
143
+ const res = await fetch(url, { method: 'GET', headers })
144
+ const body = /** @type {any} */ (await res.json().catch(() => ({})))
145
+ if (res.ok) return body.data.attributes
146
+ const first = (body.errors && body.errors[0]) || {}
147
+ const detail = first.message || first.detail || res.statusText || ''
148
+ if (res.status === 401) throw Object.assign(new Error(`rbac inspect: not authenticated (401) — check --token / --iam`), { status: 401 })
149
+ if (res.status === 403) throw Object.assign(new Error(`rbac inspect: forbidden (403) — needs saaslayer:principals authority over ${ref}: ${detail}`), { status: 403 })
150
+ if (res.status === 404) throw Object.assign(new Error(`rbac inspect: ${ref} not found (404) — or you have no saaslayer:principals authority where it lives`), { status: 404 })
151
+ if (res.status === 409) throw Object.assign(new Error(`rbac inspect: the doc changed while paging (409 PermissionDocChanged) — restart without a page cursor`), { status: 409 })
152
+ throw Object.assign(new Error(`rbac inspect failed (${res.status}): ${detail}`), { status: res.status })
153
+ }
154
+
155
+ /**
156
+ * @param {string[]} positional [ref]
157
+ * @param {{ 'api-base'?: string, token?: string, iam?: string, region?: string, profile?: string, scope?: string|string[], 'scope-page'?: string,
158
+ * 'assignment-page'?: string, 'all-scopes'?: boolean, stored?: boolean, json?: boolean }} flags
159
+ * @param {{ exchange?: typeof exchangeIamToken, print?: (s: string) => void }} [deps]
160
+ * @returns {Promise<string>} what was printed
161
+ */
162
+ async function rbacInspect(positional, flags, deps = {}) {
163
+ const ref = parseRef(positional[0])
164
+ const refText = ref.kind === 'session' ? `session:${ref.id}` : `${ref.type}:${ref.id}`
165
+ const apiBase = String(flags['api-base'] || process.env.SAASLAYER_API_BASE || '').replace(/\/$/, '')
166
+ if (!apiBase) throw new Error('rbac inspect: --api-base (or $SAASLAYER_API_BASE) is required')
167
+ const headers = await authHeaders(apiBase, flags, { exchange: deps.exchange || exchangeIamToken })
168
+ const print = deps.print || ((/** @type {string} */ s) => console.log(s))
169
+ const emit = (/** @type {string} */ s) => { print(s); return s }
170
+
171
+ if (ref.kind === 'session') {
172
+ const a = await getAttributes(`${apiBase}/sessions/${encodeURIComponent(ref.id)}/permissions?view=stored&format=inspection`, headers, refText)
173
+ if (flags.json) return emit(JSON.stringify(a, null, 2))
174
+ if (!a.inspection) return emit(`${refText} (no stored permission set)`)
175
+ return emit(formatInspection(a.inspection, { ref: refText, session: a.session }))
176
+ }
177
+
178
+ const base = `${apiBase}/principals/${encodeURIComponent(ref.type)}/${encodeURIComponent(ref.id)}/permissions`
179
+ if (flags.stored) {
180
+ if (flags.json) return emit(JSON.stringify(await getAttributes(`${base}?view=stored`, headers, refText), null, 2))
181
+ const a = await getAttributes(`${base}?view=stored&format=inspection`, headers, refText)
182
+ if (!a.inspection) return emit(`${refText} (no stored doc — not materialized)`)
183
+ return emit(formatInspection(a.inspection, { ref: refText }))
184
+ }
185
+
186
+ const scopes = flags.scope === undefined ? [] : (Array.isArray(flags.scope) ? flags.scope : [flags.scope])
187
+ /** @param {{ scopeCursor?: string|null }} [page] */
188
+ const query = (page = {}) => {
189
+ const q = new URLSearchParams()
190
+ for (const s of scopes) q.append('scope', String(s))
191
+ const scopeCursor = page.scopeCursor !== undefined ? page.scopeCursor : flags['scope-page']
192
+ if (scopeCursor) q.set('scopeCursor', String(scopeCursor))
193
+ if (flags['assignment-page']) q.set('assignmentCursor', String(flags['assignment-page']))
194
+ const s = q.toString()
195
+ return s ? `${base}?${s}` : base
196
+ }
197
+
198
+ if (!flags['all-scopes']) {
199
+ const view = await getAttributes(query(), headers, refText)
200
+ if (flags.json) return emit(JSON.stringify(view, null, 2))
201
+ const stored = await getAttributes(`${base}?view=stored&format=inspection`, headers, refText)
202
+ return emit(formatExpanded(view, { ref: refText, inspection: stored.inspection }))
203
+ }
204
+
205
+ // --all-scopes: follow the scope cursor to the end; a rebuild mid-way (409) restarts once from the first page
206
+ for (let attempt = 0; attempt < 2; attempt++) {
207
+ try {
208
+ const first = await getAttributes(query({ scopeCursor: null }), headers, refText)
209
+ const scoped = { ...first.scoped }
210
+ let cursor = first.meta && first.meta.nextScopeCursor
211
+ while (cursor) {
212
+ const next = await getAttributes(query({ scopeCursor: cursor }), headers, refText)
213
+ Object.assign(scoped, next.scoped)
214
+ cursor = next.meta && next.meta.nextScopeCursor
215
+ }
216
+ const view = { ...first, scoped, meta: { ...first.meta, nextScopeCursor: null } }
217
+ if (flags.json) return emit(JSON.stringify(view, null, 2))
218
+ const stored = await getAttributes(`${base}?view=stored&format=inspection`, headers, refText)
219
+ return emit(formatExpanded(view, { ref: refText, inspection: stored.inspection }))
220
+ } catch (err) {
221
+ if (/** @type {any} */ (err).status !== 409 || attempt === 1) throw err
222
+ console.error('rbac inspect: the doc was rebuilt while paging (409) — restarting from the first page')
223
+ }
224
+ }
225
+ throw new Error('rbac inspect: unreachable')
226
+ }
227
+
228
+ module.exports = { rbacInspect, parseRef, formatExpanded, formatInspection, formatSize }
@@ -0,0 +1,17 @@
1
+ // `saaslayer stacks` (ctsc.5) — list the vendable stacks a project can deploy (from the BFF catalog).
2
+ 'use strict'
3
+ const { apiCall } = require('../api-client')
4
+
5
+ async function stacks(flags) {
6
+ const res = await apiCall('GET', '/api/stacks', undefined, flags)
7
+ const rows = res.data || []
8
+ console.log('Deployable stacks:')
9
+ for (const r of rows) {
10
+ const a = r.attributes || {}
11
+ console.log(` ${a.service || r.id}${a.description ? ' — ' + a.description : ''}`)
12
+ }
13
+ console.log('\nDeploy with: saaslayer deploy --services <a,b>')
14
+ return rows
15
+ }
16
+
17
+ module.exports = { stacks }