saaslayer 0.0.7 → 0.2.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 (48) hide show
  1. package/README.md +150 -13
  2. package/bin/saaslayer.js +318 -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/aws.js +55 -6
  10. package/src/commands/catalog.js +30 -29
  11. package/src/commands/context.js +64 -0
  12. package/src/commands/deploy.js +79 -10
  13. package/src/commands/first-admin.js +42 -0
  14. package/src/commands/foundation.js +456 -0
  15. package/src/commands/integration-credentials.js +66 -0
  16. package/src/commands/lifecycle.js +77 -40
  17. package/src/commands/login.js +200 -26
  18. package/src/commands/machine-trust.js +96 -0
  19. package/src/commands/operations.js +140 -0
  20. package/src/commands/orgs.js +29 -4
  21. package/src/commands/{rbac-inspect.js → permissions-inspect.js} +15 -15
  22. package/src/commands/release-manifest.js +138 -0
  23. package/src/commands/service-principals.js +81 -0
  24. package/src/commands/settings.js +140 -0
  25. package/src/commands/stacks.js +12 -7
  26. package/src/commands/users-management.js +401 -0
  27. package/src/commands/users.js +192 -4
  28. package/src/config.js +20 -7
  29. package/src/credentials.js +221 -34
  30. package/src/deployment-api-auth.js +61 -0
  31. package/src/deployment-auth.js +38 -0
  32. package/src/deployments.js +12 -13
  33. package/src/discovery.js +66 -0
  34. package/src/env-compare.js +143 -0
  35. package/src/iam-session.js +4 -30
  36. package/src/module-catalog.js +66 -0
  37. package/src/permissions-request.js +43 -0
  38. package/src/release-manifest.js +334 -0
  39. package/src/scope.js +114 -0
  40. package/src/settings.js +272 -0
  41. package/src/users-api.js +165 -0
  42. package/src/users-import/import.js +10 -10
  43. package/templates/saaslayer-foundation-region.yml +37 -1
  44. package/templates/saaslayer-foundation.yml +63 -10
  45. package/src/commands/iam-principals.js +0 -53
  46. package/src/rbac-auth.js +0 -25
  47. package/vendor/ids/index.d.ts +0 -21
  48. 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')
@@ -16,6 +16,12 @@
16
16
  # it is the deployment-artifact spine that rollback, provenance, supply-chain scanning, and audit hang off.
17
17
  # Likely future occupants (not built yet — this stack is designed to hold them): a per-region KMS key, an
18
18
  # access-log bucket, an ops-alert SNS topic, deploy-notification queues, VPC endpoints.
19
+ #
20
+ # OPTIONAL — the account's email sender domain (EmailSenderDomain). An SES identity belongs to an account+region,
21
+ # not to one deployment, so it lives here. This stack is installed with the CUSTOMER's own credentials
22
+ # (`saaslayer aws connect` / `saaslayer foundation upgrade --email-sender-domain`), so SaaSLayer's deploy role never
23
+ # creates or verifies identities (tests/bootstrap.test.js). The DKIM records it outputs go into the customer's DNS;
24
+ # once verified, deployments send through it via the user-service CognitoEmailSenderArn setting.
19
25
  AWSTemplateFormatVersion: '2010-09-09'
20
26
  Description: >-
21
27
  SaaSLayer per-region foundation stack: region-bound resources for a SaaSLayer host account, starting
@@ -33,6 +39,16 @@ Parameters:
33
39
  deployer refs.ts) and passes it, guaranteeing the bucket and the injected SERVERLESS_DEPLOYMENT_BUCKET
34
40
  agree byte-for-byte. Opaque (no raw account id) so a globally-probeable S3 name never confirms the
35
41
  account is SaaSLayer-managed.
42
+ EmailSenderDomain:
43
+ Type: String
44
+ Default: ''
45
+ AllowedPattern: '^(([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63})?$'
46
+ Description: >-
47
+ Optional domain this account sends email from (e.g. acme.com). When set, an SES identity with Easy DKIM is
48
+ created and its three DKIM CNAME records are output for the domain's DNS. Empty = no sender domain.
49
+
50
+ Conditions:
51
+ HasEmailSenderDomain: !Not [!Equals [!Ref EmailSenderDomain, '']]
36
52
 
37
53
  Mappings:
38
54
  # Per-region foundation template version (semver). BUMP on every change so ops can tell which regional
@@ -40,7 +56,7 @@ Mappings:
40
56
  # saaslayer-foundation: major = breaking change (resource replaced/removed), minor = additive, patch = docs.
41
57
  Meta:
42
58
  FoundationRegion:
43
- Version: '1.0.0'
59
+ Version: '1.1.0'
44
60
 
45
61
  Resources:
46
62
  # Shared deployment-artifact bucket. Serverless namespaces every deploy under
@@ -100,7 +116,27 @@ Resources:
100
116
  Bool:
101
117
  aws:SecureTransport: 'false'
102
118
 
119
+ # The account's email sender domain (see the header). Easy DKIM: SES generates the keys and rotates them; the
120
+ # customer adds the three CNAMEs in EmailSenderDkimRecords to the domain's DNS to verify it.
121
+ EmailSenderIdentity:
122
+ Type: AWS::SES::EmailIdentity
123
+ Condition: HasEmailSenderDomain
124
+ Properties:
125
+ EmailIdentity: !Ref EmailSenderDomain
126
+
103
127
  Outputs:
128
+ EmailSenderIdentityArn:
129
+ Condition: HasEmailSenderDomain
130
+ Description: SES identity ARN of the account's email sender domain (the user-service CognitoEmailSenderArn setting).
131
+ Value: !Sub arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${EmailSenderDomain}
132
+ EmailSenderDkimRecords:
133
+ Condition: HasEmailSenderDomain
134
+ Description: The three DKIM CNAME records ('name CNAME value', one per line) to add to the sender domain's DNS.
135
+ Value: !Join
136
+ - "\n"
137
+ - - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName1, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue1]]
138
+ - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName2, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue2]]
139
+ - !Join [' ', [!GetAtt EmailSenderIdentity.DkimDNSTokenName3, CNAME, !GetAtt EmailSenderIdentity.DkimDNSTokenValue3]]
104
140
  ArtifactsBucketName:
105
141
  Description: Shared deployment-artifact bucket every SaaSLayer service in this account+region deploys into.
106
142
  Value: !Ref DeploymentArtifactBucket