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
@@ -0,0 +1,272 @@
1
+ // Module settings on the CLI side: --set MODULE.Setting=VALUE flags and settings files as a per-module patch, the
2
+ // client-side check of a patch against each module's published settings schema, and rendering that never shows a secret.
3
+ 'use strict'
4
+ const fs = require('fs')
5
+
6
+ /**
7
+ * @typedef {{ name: string, type: string, description: string, group: string, updateBehavior: 'update-safe'|'create-only',
8
+ * billingImpact: boolean, kind: 'deployment'|'runtime', secret: boolean, default?: unknown, allowed?: string[],
9
+ * pattern?: string, patternDescription?: string, min?: number, max?: number, env?: string }} Setting
10
+ * @typedef {{ module: string, revision: string, settings: Setting[], bindings?: Array<{ name: string, from: string }> }} SettingsSchema
11
+ * @typedef {Record<string, Record<string, unknown>>} SettingsPatch module → setting name → value
12
+ */
13
+
14
+ // Mirrors the control-plane API's SSM parameter-name rule for secret references.
15
+ const SSM_PARAMETER_NAME = /^\/[A-Za-z0-9_.\-/]{1,2047}$/
16
+ const SSM_PREFIX = 'ssm:'
17
+ // Mirrors the deployer's value rules (module-contracts.ts settingValueProblem); the server stays authoritative.
18
+ const ORIGIN_PATTERN = '^https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?$'
19
+ const ORIGIN_LIST_PATTERN = '^(https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?(\\s*,\\s*https?://[A-Za-z0-9.-]+(:[0-9]{1,5})?)*)?$'
20
+ const EMAIL_ADDRESS = '[^<>@\\s]+@[^<>@\\s]+'
21
+ const EMAIL_PATTERN = new RegExp(`^(${EMAIL_ADDRESS}|[^<>]*<${EMAIL_ADDRESS}>)$`)
22
+ const STRING_TYPES = new Set(['string', 'csv', 'email', 'json', 'origin', 'origin-list'])
23
+ // Environments whose settings writes and release moves need a written reason (the deployer's UPDATE_REASON_REQUIRED).
24
+ const PROTECTED_ENVS = new Set(['prod', 'staging'])
25
+
26
+ /**
27
+ * `<flag> <module>.<Setting>=<value>` flags (repeatable) as a patch. The value may contain '=' or ','.
28
+ * @param {unknown} raw the flag value(s) from parseArgs
29
+ * @param {string} flag the flag name for messages (--set, --param)
30
+ * @returns {SettingsPatch|undefined}
31
+ */
32
+ function parseSetFlags(raw, flag) {
33
+ if (raw === undefined) return undefined
34
+ /** @type {SettingsPatch} */
35
+ const patch = {}
36
+ for (const entry of Array.isArray(raw) ? raw : [raw]) {
37
+ const m = typeof entry === 'string' ? /^([^.=]+)\.([^=]+)=(.*)$/s.exec(entry) : null
38
+ if (!m) throw new Error(`${flag} expects <module>.<Setting>=<value>, e.g. ${flag} user-service.AllowedAppOrigins=https://app.example.com`)
39
+ const [, module, name, value] = m
40
+ patch[module] = { ...(patch[module] || {}), [name]: value }
41
+ }
42
+ return patch
43
+ }
44
+
45
+ /**
46
+ * A settings file: `{ "<module>": { "<Setting>": value } }`. Values are strings, numbers, booleans, null (reset to
47
+ * the default) or `{ "ssmParameter": "/name" }` for a secret. The file is input to one command, not stored state.
48
+ * @param {string} file
49
+ * @returns {SettingsPatch}
50
+ */
51
+ function readSettingsFile(file) {
52
+ let doc
53
+ try {
54
+ doc = JSON.parse(fs.readFileSync(file, 'utf8'))
55
+ } catch (err) {
56
+ throw new Error(`--settings/--file ${file}: ${err.code === 'ENOENT' ? 'file not found' : 'not valid JSON'}`)
57
+ }
58
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
59
+ if (!isObject(doc) || !Object.values(doc).every(isObject)) {
60
+ throw new Error(`${file} must be { "<module>": { "<Setting>": value } }`)
61
+ }
62
+ return doc
63
+ }
64
+
65
+ /**
66
+ * Merge patches left to right; a later value for the same setting wins (flags override a file).
67
+ * @param {...(SettingsPatch|undefined)} patches
68
+ * @returns {SettingsPatch|undefined}
69
+ */
70
+ function mergePatches(...patches) {
71
+ const present = patches.filter(Boolean)
72
+ if (!present.length) return undefined
73
+ /** @type {SettingsPatch} */
74
+ const out = {}
75
+ for (const p of present) for (const [module, values] of Object.entries(p)) out[module] = { ...(out[module] || {}), ...values }
76
+ return out
77
+ }
78
+
79
+ /**
80
+ * What a value must be, or null when it fits the setting's type, allowed values, bounds and pattern.
81
+ * @param {Setting} setting
82
+ * @param {unknown} value
83
+ * @returns {string|null}
84
+ */
85
+ function valueProblem(setting, value) {
86
+ if (!['string', 'number', 'boolean'].includes(typeof value)) return 'a string, number, or boolean'
87
+ const text = String(value)
88
+ if (setting.type === 'bool' && text !== 'true' && text !== 'false') return "'true' or 'false'"
89
+ if (setting.type === 'enum' && !(setting.allowed || []).includes(text)) return `one of ${(setting.allowed || []).join(', ')}`
90
+ if (setting.type === 'number') {
91
+ const n = typeof value === 'number' ? value : (text.trim() === '' ? NaN : Number(text))
92
+ const range = setting.min !== undefined || setting.max !== undefined ? ` between ${setting.min ?? '-∞'} and ${setting.max ?? '∞'}` : ''
93
+ if (!Number.isFinite(n) || (setting.min !== undefined && n < setting.min) || (setting.max !== undefined && n > setting.max)) return `a number${range}`
94
+ }
95
+ if (STRING_TYPES.has(setting.type) && text === '' && !setting.pattern) return null
96
+ const pattern = setting.pattern ?? (setting.type === 'origin' ? ORIGIN_PATTERN : setting.type === 'origin-list' ? ORIGIN_LIST_PATTERN : undefined)
97
+ if (pattern && !new RegExp(pattern).test(text)) return setting.patternDescription || `a value matching ${pattern}`
98
+ if (setting.type === 'email' && !EMAIL_PATTERN.test(text)) return "an email address like no-reply@example.com or 'Acme <no-reply@example.com>'"
99
+ if (setting.type === 'json') {
100
+ try { JSON.parse(text) } catch { return 'a JSON document' }
101
+ }
102
+ return null
103
+ }
104
+
105
+ /**
106
+ * The SSM parameter name a secret value references (`ssm:/name` or `{ "ssmParameter": "/name" }`), else null.
107
+ * @param {unknown} value
108
+ * @returns {string|null}
109
+ */
110
+ function secretReference(value) {
111
+ const name = typeof value === 'string' && value.startsWith(SSM_PREFIX)
112
+ ? value.slice(SSM_PREFIX.length)
113
+ : value !== null && typeof value === 'object' && Object.keys(value).length === 1 ? /** @type {{ ssmParameter?: unknown }} */ (value).ssmParameter : null
114
+ return typeof name === 'string' && SSM_PARAMETER_NAME.test(name) ? name : null
115
+ }
116
+
117
+ /**
118
+ * Check a patch against each module's schema before anything is sent. Messages name the setting, never its value.
119
+ * On update a secret is sent as `{ ssmParameter }` and null resets a setting; on create a secret is sent as its
120
+ * parameter name and null is refused. Create-only and runtime settings are refused on update.
121
+ * @param {SettingsPatch} patch
122
+ * @param {Record<string, SettingsSchema>} schemas by module
123
+ * @param {{ op: 'create'|'update' }} opts
124
+ * @returns {{ patch: SettingsPatch, createOnly: string[], billing: string[] }}
125
+ */
126
+ function checkPatch(patch, schemas, { op }) {
127
+ /** @type {SettingsPatch} */
128
+ const out = {}
129
+ const createOnly = []
130
+ const billing = []
131
+ for (const [module, values] of Object.entries(patch)) {
132
+ const schema = schemas[module]
133
+ if (!schema) throw new Error(`${module} is not ${op === 'update' ? 'deployed in this deployment' : 'a module with a settings schema'}`)
134
+ const byName = new Map(schema.settings.map((s) => [s.name, s]))
135
+ out[module] = {}
136
+ for (const [name, value] of Object.entries(values)) {
137
+ const label = `${module}.${name}`
138
+ const setting = byName.get(name)
139
+ if (!setting) {
140
+ const bound = (schema.bindings || []).find((b) => b.name === name)
141
+ if (bound) throw new Error(`${label} is bound to ${bound.from} and cannot be set`)
142
+ throw new Error(`${label} is not a setting of ${module} at revision ${schema.revision} — see: saaslayer settings schema --module ${module}`)
143
+ }
144
+ if (op === 'update' && setting.updateBehavior === 'create-only') {
145
+ throw new Error(`${label} is create-only: it is set when the deployment is created and cannot be changed on a standing deployment`)
146
+ }
147
+ if (op === 'update' && setting.kind === 'runtime') {
148
+ throw new Error(`${label} is a runtime setting; runtime settings cannot be written through the control plane yet (nothing was sent)`)
149
+ }
150
+ if (setting.updateBehavior === 'create-only') createOnly.push(label)
151
+ if (setting.billingImpact) billing.push(label)
152
+ if (value === null) {
153
+ if (op === 'create') throw new Error(`${label}: null resets a setting on a standing deployment; leave it out on create`)
154
+ out[module][name] = null
155
+ continue
156
+ }
157
+ if (setting.secret) {
158
+ const ref = secretReference(value)
159
+ if (!ref) throw new Error(`${label} is secret: pass a reference ssm:/<parameter name> (or { "ssmParameter": "/<name>" } in a file), never the value`)
160
+ out[module][name] = op === 'update' ? { ssmParameter: ref } : ref
161
+ continue
162
+ }
163
+ const problem = valueProblem(setting, value)
164
+ if (problem) throw new Error(`${label} must be ${problem}`)
165
+ out[module][name] = value
166
+ }
167
+ }
168
+ return { patch: out, createOnly, billing }
169
+ }
170
+
171
+ /**
172
+ * A setting's value for display: a secret shows only whether it is set.
173
+ * @param {{ secret: boolean, value?: unknown, isSet?: boolean }} s
174
+ * @returns {string}
175
+ */
176
+ function displayValue(s) {
177
+ if (s.secret) return s.isSet ? '(secret: set)' : '(secret: unset)'
178
+ if (s.value === undefined || s.value === null) return '—'
179
+ return typeof s.value === 'string' ? s.value : JSON.stringify(s.value)
180
+ }
181
+
182
+ /**
183
+ * @param {SettingsSchema} schema
184
+ * @returns {string[]}
185
+ */
186
+ function formatSchema(schema) {
187
+ const lines = [`${schema.module} @ ${schema.revision}: ${schema.settings.length} setting(s)`]
188
+ for (const s of schema.settings) {
189
+ const flags = [s.type, s.updateBehavior, s.kind, s.secret ? 'secret' : null, s.billingImpact ? 'billing' : null].filter(Boolean).join(', ')
190
+ const dflt = s.secret || s.default === undefined ? '' : ` default: ${JSON.stringify(s.default)}`
191
+ const allowed = s.allowed ? ` allowed: ${s.allowed.join('|')}` : ''
192
+ lines.push(` ${s.name} [${flags}] (${s.group})${dflt}${allowed}`)
193
+ lines.push(` ${s.description}`)
194
+ }
195
+ for (const b of schema.bindings || []) lines.push(` ${b.name} [bound to ${b.from}; not settable]`)
196
+ return lines
197
+ }
198
+
199
+ /**
200
+ * @typedef {{ deploymentId: string, settingsRevision: number,
201
+ * pending: { operationId: string, status: string|null, settings: Record<string, string[]> }|null,
202
+ * modules: Array<{ module: string, ref?: string, revision: string|null, schemaError: string|null, settings: Array<Setting & { value: unknown, source: string, isSet: boolean }> }> }} DeploymentSettings
203
+ */
204
+
205
+ /**
206
+ * @param {DeploymentSettings} attrs
207
+ * @returns {string[]}
208
+ */
209
+ function formatSettings(attrs) {
210
+ const lines = [`settings revision ${attrs.settingsRevision}`]
211
+ if (attrs.pending) {
212
+ const names = Object.entries(attrs.pending.settings).flatMap(([m, list]) => list.map((n) => `${m}.${n}`))
213
+ lines.push(`pending: operation ${attrs.pending.operationId} (${attrs.pending.status || '—'})${names.length ? ` applying ${names.join(', ')}` : ''}`)
214
+ }
215
+ for (const m of attrs.modules) {
216
+ lines.push(`${m.module} @ ${m.revision || '—'}`)
217
+ if (m.schemaError) { lines.push(` (no settings schema: ${m.schemaError})`); continue }
218
+ for (const s of m.settings) {
219
+ const marks = [s.updateBehavior === 'create-only' ? 'create-only' : null, s.kind === 'runtime' ? 'runtime' : null].filter(Boolean)
220
+ lines.push(` ${s.name} = ${displayValue(s)} (${s.source}${marks.length ? `; ${marks.join(', ')}` : ''})`)
221
+ }
222
+ }
223
+ return lines
224
+ }
225
+
226
+ /**
227
+ * Settings that differ between two deployments. A secret compares set/unset only.
228
+ * @param {DeploymentSettings} a
229
+ * @param {DeploymentSettings} b
230
+ * @returns {Array<{ module: string, name: string, a: string, b: string }>}
231
+ */
232
+ function diffSettings(a, b) {
233
+ /** @param {DeploymentSettings} d */
234
+ const index = (d) => new Map(d.modules.flatMap((m) => m.settings.map((s) => [`${m.ref || m.module}.${s.name}`, s])))
235
+ const left = index(a)
236
+ const right = index(b)
237
+ const keys = [...new Set([...left.keys(), ...right.keys()])].sort()
238
+ const rows = []
239
+ for (const key of keys) {
240
+ const l = left.get(key)
241
+ const r = right.get(key)
242
+ const lv = l ? displayValue(l) : '(not deployed)'
243
+ const rv = r ? displayValue(r) : '(not deployed)'
244
+ if (lv === rv) continue
245
+ const [module, ...rest] = key.split('.')
246
+ rows.push({ module, name: rest.join('.'), a: lv, b: rv })
247
+ }
248
+ return rows
249
+ }
250
+
251
+ /**
252
+ * The change a patch makes, one line per setting. A secret line names the setting and never the reference or value.
253
+ * @param {SettingsPatch} patch checked patch
254
+ * @param {DeploymentSettings} current
255
+ * @returns {string[]}
256
+ */
257
+ function formatChanges(patch, current) {
258
+ const lines = []
259
+ for (const [module, values] of Object.entries(patch)) {
260
+ const mod = current.modules.find((m) => m.module === module)
261
+ for (const [name, value] of Object.entries(values)) {
262
+ const s = mod && mod.settings.find((x) => x.name === name)
263
+ const label = `${module}.${name}`
264
+ if (s && s.secret) lines.push(` ${label}: ${value === null ? 'secret reset to its default' : 'secret reference updated'}`)
265
+ else if (value === null) lines.push(` ${label}: ${s ? displayValue(s) : '—'} → (default${s && s.default !== undefined ? ` ${JSON.stringify(s.default)}` : ''})`)
266
+ else lines.push(` ${label}: ${s ? displayValue(s) : '—'} → ${typeof value === 'string' ? value : JSON.stringify(value)}`)
267
+ }
268
+ }
269
+ return lines
270
+ }
271
+
272
+ module.exports = { PROTECTED_ENVS, parseSetFlags, readSettingsFile, mergePatches, valueProblem, secretReference, checkPatch, displayValue, formatSchema, formatSettings, diffSettings, formatChanges }
@@ -0,0 +1,165 @@
1
+ // A deployment's user-service /api/users for CLI commands: create (durable operation, Idempotency-Key), operation status,
2
+ // lookup and paging, profile updates, sign-in state, passwords, adoption and delete — with the auth headers a caller gives.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+
6
+ /**
7
+ * @typedef {{ apiBase: string, headers: () => Promise<Record<string, string>> }} UsersTarget
8
+ * apiBase = the deployment's user-service API; headers = the auth headers for each request
9
+ * @typedef {{ fetch?: typeof fetch }} Deps
10
+ * @typedef {{ name: string, status: string, error?: { code?: string, message?: string }, nextAction?: string }} OperationComponent
11
+ * @typedef {{ id: string, kind: string, status: string, components: OperationComponent[] }} Operation
12
+ * @typedef {{ id: string, attributes: Record<string, unknown> }} User
13
+ * @typedef {{ email: string, password?: string, name?: string, soid?: string, suid?: string, delivery?: 'none'|'invitation' }} CreateAttributes
14
+ */
15
+
16
+ /** A refusal from user-service, with its HTTP status and error code. */
17
+ class UsersApiError extends Error {
18
+ /** @param {number} status @param {string} code @param {string} message */
19
+ constructor(status, code, message) {
20
+ super(message)
21
+ this.status = status
22
+ this.code = code
23
+ }
24
+ }
25
+
26
+ /** @param {string} suid @param {string} [action] */
27
+ const userPath = (suid, action) => `/api/users/${encodeURIComponent(suid)}${action ? `/${action}` : ''}`
28
+
29
+ /** @param {Record<string, string|number|undefined>} params */
30
+ function query(params) {
31
+ const p = new URLSearchParams()
32
+ for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') p.set(k, String(v))
33
+ const s = p.toString()
34
+ return s ? `?${s}` : ''
35
+ }
36
+
37
+ /** @param {{ id: string, attributes?: Record<string, unknown> }} d @returns {User} */
38
+ const toUser = (d) => ({ id: d.id, attributes: d.attributes || {} })
39
+
40
+ /**
41
+ * The default Idempotency-Key for creating this email: the same key on every run, so re-running the same create
42
+ * replays its operation (same body) or is refused (another body). Holds a digest, never the email itself.
43
+ * @param {string} email
44
+ */
45
+ function defaultCreateKey(email) {
46
+ return `saaslayer-cli:users.create:${crypto.createHash('sha256').update(String(email).trim().toLowerCase()).digest('hex')}`
47
+ }
48
+
49
+ /**
50
+ * The users API of one deployment; refusals throw UsersApiError.
51
+ * @param {UsersTarget} target @param {Deps} [deps]
52
+ */
53
+ function usersApi(target, { fetch: fetchImpl = fetch } = {}) {
54
+ if (!target.apiBase) throw new Error('users api: apiBase is required')
55
+ const base = target.apiBase.replace(/\/+$/, '')
56
+
57
+ /**
58
+ * @param {string} method @param {string} path @param {{ body?: unknown, headers?: Record<string, string> }} [opts]
59
+ * @returns {Promise<{ status: number, body: any }>}
60
+ */
61
+ async function call(method, path, opts = {}) {
62
+ const res = await fetchImpl(`${base}${path}`, {
63
+ method,
64
+ headers: { 'content-type': 'application/json', ...(await target.headers()), ...(opts.headers || {}) },
65
+ ...(opts.body === undefined ? {} : { body: JSON.stringify(opts.body) }),
66
+ })
67
+ const body = await res.json().catch(() => ({}))
68
+ if (!res.ok) {
69
+ const errors = body.errors || []
70
+ const code = (errors[0] && errors[0].code) || 'ERROR'
71
+ const detail = errors.map((e) => e.message || e.detail).filter(Boolean).join('; ') || `HTTP ${res.status}`
72
+ throw new UsersApiError(res.status, code, `${method} ${path.split('?')[0]} refused (${res.status} ${code}: ${detail})`)
73
+ }
74
+ return { status: res.status, body }
75
+ }
76
+
77
+ return {
78
+ /**
79
+ * Create a user as a durable operation. 201 created, 200 replayed or already provisioned, 202 unfinished (follow the
80
+ * operation, or retry with the same key and body). A password needs users:set-password and EnablePasswordInitialization.
81
+ * @param {CreateAttributes} attributes @param {string} idempotencyKey
82
+ * @returns {Promise<{ status: number, user: User|null, operation: Operation }>}
83
+ */
84
+ async create(attributes, idempotencyKey) {
85
+ const attrs = Object.fromEntries(Object.entries(attributes).filter(([, v]) => v !== undefined))
86
+ const { status, body } = await call('POST', '/api/users', { headers: { 'idempotency-key': idempotencyKey }, body: { data: { attributes: attrs } } })
87
+ return { status, user: body.data ? toUser(body.data) : null, operation: body.meta && body.meta.operation }
88
+ },
89
+ /** @param {string} id @returns {Promise<Operation>} */
90
+ async getOperation(id) {
91
+ return (await call('GET', `/api/users/operations/${encodeURIComponent(id)}`)).body.data.attributes
92
+ },
93
+ /** @param {string} suid @param {{ org?: string }} [opts] @returns {Promise<User>} */
94
+ async get(suid, { org } = {}) {
95
+ return toUser((await call('GET', `${userPath(suid)}${query({ org })}`)).body.data)
96
+ },
97
+ /**
98
+ * One page of users holding an email or whose default org is X (the projection).
99
+ * @param {{ email?: string, defaultOrg?: string }} by @param {{ limit?: number, cursor?: string }} [page]
100
+ * @returns {Promise<{ users: User[], nextCursor: string|null }>}
101
+ */
102
+ async list(by, { limit, cursor } = {}) {
103
+ const { body } = await call('GET', `/api/users${query({ email: by.email, defaultOrg: by.email ? undefined : by.defaultOrg, limit, cursor })}`)
104
+ const next = body.links && body.links.next ? new URL(body.links.next, 'http://next').searchParams.get('cursor') : null
105
+ return { users: (body.data || []).map(toUser), nextCursor: next }
106
+ },
107
+ /** The suid of the user holding this email (users:read). @param {string} email */
108
+ async findSuid(email) {
109
+ const [found] = (await this.list({ email })).users
110
+ if (!found) throw new Error(`users api: no user with email ${email}`)
111
+ return found.id
112
+ },
113
+ /** @param {string} suid @param {Record<string, string>} attributes @returns {Promise<User>} */
114
+ async update(suid, attributes) {
115
+ return toUser((await call('PATCH', userPath(suid), { body: { data: { attributes } } })).body.data)
116
+ },
117
+ /** @param {string} suid @returns {Promise<User>} */
118
+ async disable(suid) {
119
+ return toUser((await call('POST', userPath(suid, 'disable'))).body.data)
120
+ },
121
+ /** @param {string} suid @returns {Promise<User>} */
122
+ async enable(suid) {
123
+ return toUser((await call('POST', userPath(suid, 'enable'))).body.data)
124
+ },
125
+ /** GDPR delete everywhere; email resolves a user that was never projected. @param {string} suid @param {{ email?: string }} [opts] */
126
+ async remove(suid, { email } = {}) {
127
+ return (await call('DELETE', `${userPath(suid)}${query({ email })}`)).body.data.attributes
128
+ },
129
+ /** @param {string} suid @returns {Promise<{ delivery: string }>} */
130
+ async resetPassword(suid) {
131
+ return (await call('POST', userPath(suid, 'reset-password'))).body.data.attributes
132
+ },
133
+ /** @param {string} suid @param {string} password @param {{ permanent?: boolean }} [opts] @returns {Promise<{ permanent: boolean }>} */
134
+ async setPassword(suid, password, { permanent = true } = {}) {
135
+ return (await call('POST', userPath(suid, 'set-password'), { body: { data: { attributes: { password, permanent } } } })).body.data.attributes
136
+ },
137
+ /** @param {string} suid @returns {Promise<{ via: string, adopted: boolean }>} */
138
+ async adopt(suid) {
139
+ return (await call('POST', userPath(suid, 'adopt'))).body.data.attributes
140
+ },
141
+ /**
142
+ * Remove the user's MFA factors so they can enroll again (audited with the reason).
143
+ * @param {string} suid @param {string} reason
144
+ * @returns {Promise<{ passkeysRemoved: number, cognitoMfaDisabled: boolean, signedOut: boolean }>}
145
+ */
146
+ async resetMfa(suid, reason) {
147
+ return (await call('POST', userPath(suid, 'reset-mfa'), { body: { data: { attributes: { reason } } } })).body.data.attributes
148
+ },
149
+ }
150
+ }
151
+
152
+ /**
153
+ * The password piped on stdin (one trailing newline dropped).
154
+ * @param {NodeJS.ReadableStream} stdin
155
+ * @returns {Promise<string>}
156
+ */
157
+ async function readPasswordFromStdin(stdin) {
158
+ let data = ''
159
+ for await (const chunk of stdin) data += chunk
160
+ const password = data.replace(/\r?\n$/, '')
161
+ if (!password) throw new Error('empty password on stdin')
162
+ return password
163
+ }
164
+
165
+ module.exports = { usersApi, readPasswordFromStdin, defaultCreateKey, UsersApiError }
@@ -1,5 +1,5 @@
1
1
  // `saaslayer users import` core: plans (reads only) and applies a manifest to a deployment with YOUR credentials — new
2
- // users via a Cognito CSV import job (reset-required, no emails sent), existing ones linked, then rbac principals, orgs,
2
+ // users via a Cognito CSV import job (reset-required, no emails sent), existing ones linked, then permissions principals, orgs,
3
3
  // members and the first Owner.
4
4
  'use strict'
5
5
  const { OWNER, displayName } = require('./manifest')
@@ -174,8 +174,8 @@ async function runImportJob(rows, plan, target, { exec, fetch, sleep, now }) {
174
174
  throw new Error(`users import: job ${created.JobId} did not finish; check it with aws cognito-idp describe-user-import-job`)
175
175
  }
176
176
 
177
- /** POST to the rbac API; returns { status, message }. */
178
- async function rbacPost(fetch, target, headers, path, body) {
177
+ /** POST to the permissions API; returns { status, message }. */
178
+ async function permissionsPost(fetch, target, headers, path, body) {
179
179
  const res = await fetch(`${target.apiBase.replace(/\/$/, '')}${path}`, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body: JSON.stringify(body) })
180
180
  const json = await res.json().catch(() => ({}))
181
181
  return { status: res.status, message: ((json.errors || [])[0] || {}).message || '' }
@@ -237,17 +237,17 @@ async function applyImport(plan, target, deps) {
237
237
  }
238
238
  }
239
239
 
240
- // 3. orgs, members, first owner — through the rbac IAM principal
240
+ // 3. orgs, members, first owner — through the permissions IAM principal
241
241
  const headers = await deps.authHeaders()
242
242
  const summary = { created: 0, linked: 0, failed: 0, skipped: 0, orgsCreated: 0, ownersGranted: 0 }
243
243
  for (const p of people.values()) summary[p.user === 'created' ? 'created' : p.user === 'linked' ? 'linked' : 'failed']++
244
- // Each person's rbac principal, created once before any membership (imported users haven't signed in yet, and
244
+ // Each person's permissions principal, created once before any membership (imported users haven't signed in yet, and
245
245
  // sign-in is what normally creates it); 409 = it already exists.
246
246
  const principals = new Map()
247
247
  const ensurePrincipal = async (email, suid) => {
248
248
  if (!principals.has(suid)) {
249
- const res = await rbacPost(fetch, target, headers, '/users', { id: suid, email })
250
- principals.set(suid, res.status === 201 || res.status === 409 ? null : `rbac user create failed (${res.status}): ${res.message}`)
249
+ const res = await permissionsPost(fetch, target, headers, '/users', { id: suid, email })
250
+ principals.set(suid, res.status === 201 || res.status === 409 ? null : `permissions user create failed (${res.status}): ${res.message}`)
251
251
  }
252
252
  return principals.get(suid)
253
253
  }
@@ -257,7 +257,7 @@ async function applyImport(plan, target, deps) {
257
257
  const active = a.users.filter((u) => u.action !== 'skip' && people.get(u.email) && people.get(u.email).suid)
258
258
  let org = 'skipped'
259
259
  if (active.length) {
260
- const res = await rbacPost(fetch, target, headers, '/orgs', { id: a.id, name: a.name })
260
+ const res = await permissionsPost(fetch, target, headers, '/orgs', { id: a.id, name: a.name })
261
261
  org = res.status === 201 ? 'created' : res.status === 409 ? 'exists' : 'failed'
262
262
  if (org === 'created') summary.orgsCreated++
263
263
  if (org === 'failed') users.push({ email: null, notes: [`org create failed (${res.status}): ${res.message}`] })
@@ -269,11 +269,11 @@ async function applyImport(plan, target, deps) {
269
269
  const principalError = person.suid && org !== 'failed' && org !== 'skipped' ? await ensurePrincipal(u.email, person.suid) : null
270
270
  if (principalError) row.notes.push(principalError)
271
271
  if (person.suid && org !== 'failed' && org !== 'skipped' && !principalError) {
272
- const member = await rbacPost(fetch, target, headers, `/orgs/${encodeURIComponent(a.id)}/members`, { type: 'user', id: person.suid })
272
+ const member = await permissionsPost(fetch, target, headers, `/orgs/${encodeURIComponent(a.id)}/members`, { type: 'user', id: person.suid })
273
273
  row.member = member.status === 201
274
274
  if (!row.member) row.notes.push(`member add failed (${member.status}): ${member.message}`)
275
275
  if (row.member && u.grant === 'owner') {
276
- const owner = await rbacPost(fetch, target, headers, `/catalog/${encodeURIComponent(target.product)}/bootstrap-owner`, { orgId: a.id, userId: person.suid })
276
+ const owner = await permissionsPost(fetch, target, headers, `/catalog/${encodeURIComponent(target.product)}/bootstrap-owner`, { orgId: a.id, userId: person.suid })
277
277
  row.owner = owner.status === 201 ? 'granted' : owner.status === 409 ? 'exists' : 'failed'
278
278
  if (row.owner === 'granted') summary.ownersGranted++
279
279
  if (row.owner === 'exists') row.notes.push('the org already has an owner; grant more owners in the product')
@@ -113,7 +113,7 @@ Mappings:
113
113
  # patch = comments/docs/no behavior change
114
114
  Meta:
115
115
  Foundation:
116
- Version: '5.9.0'
116
+ Version: '5.12.0'
117
117
 
118
118
  Resources:
119
119
  # The shared deployment-artifact bucket moved OUT of this account-global stack into the per-region
@@ -570,12 +570,17 @@ Resources:
570
570
  - cognito-idp:AdminDeleteUser
571
571
  - cognito-idp:AdminDeleteUserAttributes
572
572
  - cognito-idp:AdminDisableProviderForUser
573
+ # User lifecycle operations by suid (user-service API: disable/enable after global sign-out, reset-password).
574
+ - cognito-idp:AdminDisableUser
575
+ - cognito-idp:AdminEnableUser
573
576
  - cognito-idp:AdminGetUser
574
577
  - cognito-idp:AdminLinkProviderForUser
575
578
  - cognito-idp:AdminListGroupsForUser
579
+ - cognito-idp:AdminResetUserPassword
576
580
  - cognito-idp:AdminSetUserMFAPreference
577
581
  - cognito-idp:AdminSetUserPassword
578
582
  - cognito-idp:AdminUpdateUserAttributes
583
+ - cognito-idp:AdminUserGlobalSignOut
579
584
  # Social login + identity stitching (epic monorepo-24667): the idpResource custom-resource
580
585
  # Lambda manages the federated IdPs; the PreSignUp/stitching + account Lambdas link/disable
581
586
  # providers, set passwords, and delete users. The boundary is the ceiling, so it must allow
@@ -647,6 +652,12 @@ Resources:
647
652
  Resource:
648
653
  - !Sub arn:${AWS::Partition}:dynamodb:*:${AWS::AccountId}:table/${StackNamePrefix}*
649
654
  - !Sub arn:${AWS::Partition}:dynamodb:*:${AWS::AccountId}:table/${StackNamePrefix}*/backup/*
655
+ # rbac's machine-trust API renders its own IAM-principals document under the deployment's SSM namespace.
656
+ - Effect: Allow
657
+ Action:
658
+ - ssm:PutParameter
659
+ Resource:
660
+ - !Sub arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:parameter/saaslayer/deployment/*
650
661
  # Transactional email from this account's own SES identities (user-service registration codes).
651
662
  - Effect: Allow
652
663
  Action:
@@ -769,11 +780,12 @@ Resources:
769
780
  - lambda:ListVersionsByFunction
770
781
  Resource: '*'
771
782
  # Post-deploy SEED data-plane: after a module deploys, the deployer runs its seed
772
- # script under this role to make the deployment usable — create the initial admin
773
- # user in the just-created Cognito pool (user-service seed) and bootstrap the tenant,
774
- # admin role, and trust policy in the rbac tables (rbac-core seed). Cognito admin
775
- # actions cannot be resource-scoped to a pool that does not exist at bootstrap time;
776
- # DynamoDB is scoped to the rbac-* managed tables.
783
+ # script under this role to make the deployment usable — bootstrap the tenant, the
784
+ # designated first admin's deployment-administrator binding (and an explicit recovery's
785
+ # rebinding) and the trust policy in the rbac tables (rbac-core seed), then create and
786
+ # deliver the first admin in the just-created Cognito pool with its core-table records
787
+ # (user-service seed). Cognito admin actions cannot be resource-scoped to a pool that does
788
+ # not exist at bootstrap time; DynamoDB is scoped to the managed-prefix tables.
777
789
  - Effect: Allow
778
790
  Action:
779
791
  - cognito-idp:AdminCreateUser
@@ -793,12 +805,17 @@ Resources:
793
805
  - dynamodb:GetItem
794
806
  - dynamodb:PutItem
795
807
  - dynamodb:UpdateItem
808
+ # rbac unbinds a role with DeleteItem (first-admin recovery, legacy admin retirement).
809
+ - dynamodb:DeleteItem
796
810
  - dynamodb:Query
797
811
  - dynamodb:BatchWriteItem
798
812
  # Teardown cleanup: a table with DeletionPolicy:Retain survives `serverless remove`, so the
799
813
  # deployer's module-runner deletes those retained sl-* tables directly after the stack is gone
800
814
  # (deleteStackOwnedTables) — else a same-named recreate collides. Scoped to sl-* tables only.
801
815
  - dynamodb:DeleteTable
816
+ # Protected-environment tables carry deletion protection; a delete-custody teardown turns it off
817
+ # (UpdateTable DeletionProtectionEnabled=false) before DeleteTable. Same sl-* scope.
818
+ - dynamodb:UpdateTable
802
819
  Resource:
803
820
  - !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${StackNamePrefix}*
804
821
  - !Sub arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${StackNamePrefix}*/index/*
@@ -1,53 +0,0 @@
1
- // `saaslayer rbac iam-principals set|get`: declare which of your AWS IAM roles are trusted SaaSLayer principals (and
2
- // their credential scopes) by writing the deployment's SSM parameter in your own account with your AWS credentials.
3
- 'use strict'
4
- const fs = require('fs')
5
- const path = require('path')
6
- const { execFileSync } = require('child_process')
7
- const { iamPrincipalsParam, validatePrincipalsFile } = require('../iam-session')
8
-
9
- /** @param {string} cmd @param {string[]} args */
10
- const defaultExec = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8' })
11
-
12
- /**
13
- * @param {{ deployment?: string, 'service-instance'?: string, region?: string, profile?: string }} flags
14
- * @returns {{ name: string, awsArgs: string[] }}
15
- */
16
- function target(flags) {
17
- if (!flags.deployment) throw new Error('rbac iam-principals: --deployment <dep_id> is required')
18
- const region = flags.region || process.env.AWS_REGION
19
- if (!region) throw new Error('rbac iam-principals: --region (or $AWS_REGION) is required')
20
- return {
21
- name: iamPrincipalsParam(flags.deployment, flags['service-instance'] || '_'),
22
- awsArgs: ['--region', region, ...(flags.profile ? ['--profile', flags.profile] : [])],
23
- }
24
- }
25
-
26
- /**
27
- * Validate the principals file and write it to the deployment's SSM parameter.
28
- * @param {string[]} positional [file]
29
- * @param {object} flags
30
- * @param {{ exec?: typeof defaultExec }} [deps]
31
- */
32
- function iamPrincipalsSet(positional, flags, { exec = defaultExec } = {}) {
33
- if (!positional[0]) throw new Error('rbac iam-principals set: a principals file is required')
34
- const config = JSON.parse(fs.readFileSync(path.resolve(positional[0]), 'utf8'))
35
- const errors = validatePrincipalsFile(config)
36
- if (errors.length) throw new Error(`rbac iam-principals set: ${errors.join('; ')}`)
37
- const { name, awsArgs } = target(flags)
38
- exec('aws', ['ssm', 'put-parameter', '--name', name, '--type', 'String', '--overwrite', '--value', JSON.stringify(config), ...awsArgs])
39
- return name
40
- }
41
-
42
- /**
43
- * Read the deployment's current IAM principals.
44
- * @param {string[]} positional
45
- * @param {object} flags
46
- * @param {{ exec?: typeof defaultExec }} [deps]
47
- */
48
- function iamPrincipalsGet(positional, flags, { exec = defaultExec } = {}) {
49
- const { name, awsArgs } = target(flags)
50
- return JSON.parse(exec('aws', ['ssm', 'get-parameter', '--name', name, '--query', 'Parameter.Value', '--output', 'text', ...awsArgs]))
51
- }
52
-
53
- module.exports = { iamPrincipalsSet, iamPrincipalsGet }
package/src/rbac-auth.js DELETED
@@ -1,25 +0,0 @@
1
- // Auth headers for calls to a deployment's rbac API from the CLI: an IAM principal token (--iam, exchanged from your
2
- // AWS identity) or an API key (--token). Shared by the catalog and users commands.
3
- 'use strict'
4
-
5
- /**
6
- * Request auth headers: an IAM principal token (--iam, exchanged from your AWS identity) as a bearer only, or a
7
- * --token sent as both api key and bearer.
8
- * @param {string} apiBase
9
- * @param {{ token?: string, iam?: string, region?: string, profile?: string }} flags
10
- * @param {{ exchange: (opts: { apiBase: string, principalId: string, region: string, profile?: string }) => Promise<string> }} deps
11
- * @returns {Promise<Record<string, string>>}
12
- */
13
- async function authHeaders(apiBase, flags, { exchange }) {
14
- if (flags.iam) {
15
- const region = flags.region || process.env.AWS_REGION || 'us-west-2'
16
- const token = await exchange({ apiBase, principalId: flags.iam, region, profile: flags.profile })
17
- return { authorization: `Bearer ${token}` }
18
- }
19
- const token = flags.token || process.env.SAASLAYER_TOKEN
20
- if (!token) throw new Error('--iam <principalId> or --token (or $SAASLAYER_TOKEN) is required')
21
- return { 'x-api-key': token, authorization: `Bearer ${token}` }
22
- }
23
-
24
-
25
- module.exports = { authHeaders }