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,292 @@
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,
3
+ // members and the first Owner.
4
+ 'use strict'
5
+ const { OWNER, displayName } = require('./manifest')
6
+
7
+ const TERMINAL_JOB_STATES = ['Succeeded', 'Failed', 'Stopped', 'Expired']
8
+ const E164 = /^\+[1-9]\d{7,14}$/
9
+
10
+ /** @param {string} value */
11
+ function csvField(value) {
12
+ const s = value == null ? '' : String(value)
13
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
14
+ }
15
+
16
+ /** @param {string[]} header @param {Array<Record<string, string>>} rows */
17
+ function toCsv(header, rows) {
18
+ return [header, ...rows.map((r) => header.map((h) => r[h] ?? ''))].map((cells) => cells.map(csvField).join(',')).join('\n') + '\n'
19
+ }
20
+
21
+ /**
22
+ * Parse CSV (RFC 4180 quoting) into objects keyed by the header row.
23
+ * @param {string} text
24
+ * @returns {Array<Record<string, string>>}
25
+ */
26
+ function parseCsv(text) {
27
+ const rows = []
28
+ let row = []
29
+ let field = ''
30
+ let quoted = false
31
+ for (let i = 0; i < text.length; i++) {
32
+ const c = text[i]
33
+ if (quoted) {
34
+ if (c === '"' && text[i + 1] === '"') { field += '"'; i++ } else if (c === '"') quoted = false
35
+ else field += c
36
+ } else if (c === '"') quoted = true
37
+ else if (c === ',') { row.push(field); field = '' }
38
+ else if (c === '\n') { row.push(field); rows.push(row); row = []; field = '' }
39
+ else if (c !== '\r') field += c
40
+ }
41
+ if (field || row.length) { row.push(field); rows.push(row) }
42
+ const [header, ...body] = rows
43
+ return body.map((cells) => Object.fromEntries(header.map((h, i) => [h, cells[i] ?? ''])))
44
+ }
45
+
46
+ /** @param {{ region: string, profile?: string, userPoolId: string }} target */
47
+ const poolArgs = (target) => ['--user-pool-id', target.userPoolId, '--region', target.region, ...(target.profile ? ['--profile', target.profile] : [])]
48
+
49
+ /**
50
+ * The import-job logs role the target pool's user-service stack publishes at /<stack>/user/pool/import-logs-role-arn,
51
+ * or null when the pool isn't a stack resource or the stack predates the role.
52
+ * @param {Function} exec
53
+ * @param {{ userPoolId: string, region: string, profile?: string }} target
54
+ * @returns {{ arn: string | null, parameter: string | null }}
55
+ */
56
+ function publishedLogsRole(exec, target) {
57
+ const scope = ['--region', target.region, ...(target.profile ? ['--profile', target.profile] : [])]
58
+ let parameter = null
59
+ try {
60
+ const resources = JSON.parse(exec('aws', ['cloudformation', 'describe-stack-resources', '--physical-resource-id', target.userPoolId, ...scope, '--output', 'json'])).StackResources || []
61
+ if (!resources.length) return { arn: null, parameter }
62
+ parameter = `/${resources[0].StackName}/user/pool/import-logs-role-arn`
63
+ return { arn: JSON.parse(exec('aws', ['ssm', 'get-parameter', '--name', parameter, ...scope, '--output', 'json'])).Parameter.Value || null, parameter }
64
+ } catch {
65
+ return { arn: null, parameter }
66
+ }
67
+ }
68
+
69
+ /** @param {Array<{ Name: string, Value: string }>} list @param {string} name */
70
+ const attr = (list, name) => ((list || []).find((a) => a.Name === name) || {}).Value || null
71
+
72
+ /**
73
+ * The pool user with this email (email is the sign-in identifier), or null.
74
+ * @returns {{ username: string, status: string, suid: string | null, soid: string | null } | null}
75
+ */
76
+ function findUser(exec, target, email) {
77
+ const out = JSON.parse(exec('aws', ['cognito-idp', 'list-users', ...poolArgs(target), '--filter', `email = "${email.replace(/"/g, '')}"`, '--output', 'json']))
78
+ const u = (out.Users || [])[0]
79
+ if (!u) return null
80
+ return { username: u.Username, status: u.UserStatus, suid: attr(u.Attributes, 'custom:suid'), soid: attr(u.Attributes, 'custom:soid') }
81
+ }
82
+
83
+ /**
84
+ * What an import would do, from reads only: which people are new (imported), already in the pool (linked), or skipped.
85
+ * A person in several accounts is one user: created (or linked) once, then a member of each account.
86
+ * @param {any} manifest a validated manifest
87
+ * @param {{ userPoolId: string, region: string, profile?: string }} target
88
+ * @param {{ exec: (cmd: string, args: string[]) => string }} deps
89
+ */
90
+ async function planImport(manifest, target, { exec }) {
91
+ if (!target.userPoolId) throw new Error('users import: --user-pool-id is required')
92
+ if (!target.region) throw new Error('users import: --region is required')
93
+ // Cognito fails the whole job if password_hash is present without a hashing algorithm; imports never carry hashes.
94
+ const header = (JSON.parse(exec('aws', ['cognito-idp', 'get-csv-header', ...poolArgs(target), '--output', 'json'])).CSVHeader || [])
95
+ .filter((column) => column !== 'password_hash')
96
+ for (const needed of ['custom:suid', 'custom:soid']) {
97
+ if (!header.includes(needed)) throw new Error(`users import: the target pool has no ${needed} attribute — is this a SaaSLayer user pool?`)
98
+ }
99
+ const seen = new Map()
100
+ const summary = { accounts: manifest.accounts.length, create: 0, link: 0, skip: 0 }
101
+ const accounts = manifest.accounts.map((account) => ({
102
+ id: account.id,
103
+ name: account.name,
104
+ users: account.users.map((u) => {
105
+ const entry = { email: u.email, role: u.role, grant: u.role === OWNER ? 'owner' : 'unsupported', source: u }
106
+ if (u.enabled === false) { summary.skip++; return { ...entry, action: 'skip', reason: 'disabled in the source' } }
107
+ if (seen.has(u.email)) return { ...entry, action: 'member', existing: seen.get(u.email).existing }
108
+ const existing = findUser(exec, target, u.email)
109
+ const action = existing ? 'link' : 'create'
110
+ summary[action]++
111
+ seen.set(u.email, { existing })
112
+ return { ...entry, action, existing, defaultOrg: account.id }
113
+ }),
114
+ }))
115
+ return { target: { userPoolId: target.userPoolId, region: target.region }, header, accounts, summary }
116
+ }
117
+
118
+ /** @param {ReturnType<typeof planImport> extends Promise<infer P> ? P : never} plan */
119
+ function formatPlan(plan, { apply = false } = {}) {
120
+ const lines = [`users import ${apply ? '' : '(dry run — nothing written) '}→ pool ${plan.target.userPoolId} (${plan.target.region})`]
121
+ for (const a of plan.accounts) {
122
+ lines.push(`account ${a.id} "${a.name}" → org ${a.id} (created, or reused if it exists)`)
123
+ let ownerNamed = false
124
+ for (const u of a.users) {
125
+ let role = `${u.role} — not granted by import; grant it in the product`
126
+ if (u.grant === 'owner' && u.action !== 'skip') {
127
+ role = ownerNamed ? 'Owner only if no one above becomes it (import makes one Owner per org)' : 'first Owner'
128
+ ownerNamed = true
129
+ }
130
+ if (u.action === 'skip') lines.push(` - ${u.email} skipped: ${u.reason}`)
131
+ else if (u.action === 'create') lines.push(` + ${u.email} new user (reset required, no email sent); default org ${u.defaultOrg}; member; ${role}`)
132
+ else if (u.action === 'link') lines.push(` = ${u.email} already in the pool (${u.existing.status}${u.existing.suid ? '' : ', no suid yet'}); member; ${role}${u.existing.soid && u.existing.soid !== u.defaultOrg ? `; default org stays ${u.existing.soid}` : ''}`)
133
+ else lines.push(` ~ ${u.email} (same person as above); member; ${role}`)
134
+ }
135
+ }
136
+ const s = plan.summary
137
+ lines.push(`${s.accounts} accounts: ${s.create} new users, ${s.link} already in the pool, ${s.skip} skipped`)
138
+ if (!apply) lines.push('Re-run with --apply to import.')
139
+ return lines.join('\n')
140
+ }
141
+
142
+ /** The CSV row for a new user: reset-required on import, email verified (the reset code proves it), their suid + org. */
143
+ function csvRow(user, suid, orgId) {
144
+ const u = user.source
145
+ return {
146
+ 'cognito:username': u.email,
147
+ email: u.email,
148
+ email_verified: 'true',
149
+ given_name: u.givenName || '',
150
+ family_name: u.familyName || '',
151
+ name: displayName(u) === u.email ? '' : displayName(u),
152
+ phone_number: E164.test(u.phone || '') ? u.phone : '',
153
+ phone_number_verified: 'false',
154
+ 'cognito:mfa_enabled': 'false',
155
+ 'custom:suid': suid,
156
+ 'custom:soid': orgId,
157
+ }
158
+ }
159
+
160
+ /** Run one Cognito CSV import job for the new users; returns its final state. */
161
+ async function runImportJob(rows, plan, target, { exec, fetch, sleep, now }) {
162
+ const args = poolArgs(target)
163
+ const created = JSON.parse(exec('aws', ['cognito-idp', 'create-user-import-job', ...args, '--job-name', `saaslayer-users-import-${now().toISOString().replace(/[:.]/g, '-')}`, '--cloud-watch-logs-role-arn', target.logsRoleArn, '--output', 'json'])).UserImportJob
164
+ const upload = await fetch(created.PreSignedUrl, { method: 'PUT', headers: { 'x-amz-server-side-encryption': 'aws:kms' }, body: toCsv(plan.header, rows) })
165
+ if (!upload.ok) throw new Error(`users import: CSV upload failed (${upload.status})`)
166
+ exec('aws', ['cognito-idp', 'start-user-import-job', ...args, '--job-id', created.JobId, '--output', 'json'])
167
+ for (let i = 0; i < 400; i++) {
168
+ const job = JSON.parse(exec('aws', ['cognito-idp', 'describe-user-import-job', ...args, '--job-id', created.JobId, '--output', 'json'])).UserImportJob
169
+ if (TERMINAL_JOB_STATES.includes(job.Status)) {
170
+ return { id: job.JobId, status: job.Status, imported: job.ImportedUsers || 0, failed: job.FailedUsers || 0, skipped: job.SkippedUsers || 0 }
171
+ }
172
+ await sleep(3000)
173
+ }
174
+ throw new Error(`users import: job ${created.JobId} did not finish; check it with aws cognito-idp describe-user-import-job`)
175
+ }
176
+
177
+ /** POST to the rbac API; returns { status, message }. */
178
+ async function rbacPost(fetch, target, headers, path, body) {
179
+ const res = await fetch(`${target.apiBase.replace(/\/$/, '')}${path}`, { method: 'POST', headers: { ...headers, 'content-type': 'application/json' }, body: JSON.stringify(body) })
180
+ const json = await res.json().catch(() => ({}))
181
+ return { status: res.status, message: ((json.errors || [])[0] || {}).message || '' }
182
+ }
183
+
184
+ /**
185
+ * Apply a plan: import new users (one CSV job), give linked users a suid and default org when missing, then create each
186
+ * account's org, add members and bootstrap the first Owner. Idempotent: a re-run skips what exists and retries failures.
187
+ * @param {any} plan from planImport
188
+ * @param {{ userPoolId: string, region: string, profile?: string, apiBase?: string, product?: string, logsRoleArn?: string }} target
189
+ * logsRoleArn defaults to the role the pool's user-service stack publishes (publishedLogsRole)
190
+ * @param {{ exec: Function, fetch: Function, mint: () => string, sleep: (ms: number) => Promise<void>, authHeaders: () => Promise<Record<string, string>>, now: () => Date }} deps
191
+ */
192
+ async function applyImport(plan, target, deps) {
193
+ const { exec, fetch, mint, now } = deps
194
+ const newUsers = new Map()
195
+ for (const a of plan.accounts) for (const u of a.users) if (u.action === 'create') newUsers.set(u.email, u)
196
+ if (!target.apiBase) throw new Error('users import: --api-base is required with --apply')
197
+ if (!target.product) throw new Error('users import: --product is required with --apply (its catalog names the owner role)')
198
+ if (newUsers.size && !target.logsRoleArn) {
199
+ const published = publishedLogsRole(exec, target)
200
+ if (!published.arn) {
201
+ throw new Error(`users import: no logs role for the import job: pass --logs-role-arn (the Cognito import job writes its log there)${published.parameter ? `; ${published.parameter} not found — deploy the user-service stack with UserImportLogsRole` : ''}`)
202
+ }
203
+ target = { ...target, logsRoleArn: published.arn }
204
+ }
205
+ const startedAt = now().toISOString()
206
+
207
+ // 1. new users through one import job
208
+ const suids = new Map()
209
+ let job = null
210
+ if (newUsers.size) {
211
+ const rows = [...newUsers.values()].map((u) => {
212
+ const suid = mint()
213
+ suids.set(u.email, suid)
214
+ return csvRow(u, suid, u.defaultOrg)
215
+ })
216
+ job = await runImportJob(rows, plan, target, deps)
217
+ }
218
+
219
+ // 2. who is in the pool now: created, linked (suid/default org filled when missing) or failed
220
+ const people = new Map()
221
+ for (const a of plan.accounts) {
222
+ for (const u of a.users) {
223
+ if (u.action !== 'create' && u.action !== 'link') continue
224
+ const notes = []
225
+ const found = findUser(exec, target, u.email)
226
+ if (!found) { people.set(u.email, { user: 'failed', suid: null, notes: ['not in the pool after the import job — see the job\'s CloudWatch log'] }); continue }
227
+ if (u.action === 'create') { people.set(u.email, { user: 'created', suid: found.suid, notes }); continue }
228
+ const updates = []
229
+ let suid = found.suid
230
+ if (!suid) { suid = mint(); updates.push({ Name: 'custom:suid', Value: suid }) }
231
+ if (!found.soid) updates.push({ Name: 'custom:soid', Value: u.defaultOrg })
232
+ else if (found.soid !== u.defaultOrg) notes.push(`default org stays ${found.soid}`)
233
+ if (updates.length) {
234
+ exec('aws', ['cognito-idp', 'admin-update-user-attributes', ...poolArgs(target), '--username', found.username, '--user-attributes', JSON.stringify(updates)])
235
+ }
236
+ people.set(u.email, { user: 'linked', suid, notes })
237
+ }
238
+ }
239
+
240
+ // 3. orgs, members, first owner — through the rbac IAM principal
241
+ const headers = await deps.authHeaders()
242
+ const summary = { created: 0, linked: 0, failed: 0, skipped: 0, orgsCreated: 0, ownersGranted: 0 }
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
245
+ // sign-in is what normally creates it); 409 = it already exists.
246
+ const principals = new Map()
247
+ const ensurePrincipal = async (email, suid) => {
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}`)
251
+ }
252
+ return principals.get(suid)
253
+ }
254
+ const accounts = []
255
+ for (const a of plan.accounts) {
256
+ const users = []
257
+ const active = a.users.filter((u) => u.action !== 'skip' && people.get(u.email) && people.get(u.email).suid)
258
+ let org = 'skipped'
259
+ if (active.length) {
260
+ const res = await rbacPost(fetch, target, headers, '/orgs', { id: a.id, name: a.name })
261
+ org = res.status === 201 ? 'created' : res.status === 409 ? 'exists' : 'failed'
262
+ if (org === 'created') summary.orgsCreated++
263
+ if (org === 'failed') users.push({ email: null, notes: [`org create failed (${res.status}): ${res.message}`] })
264
+ }
265
+ for (const u of a.users) {
266
+ if (u.action === 'skip') { summary.skipped++; users.push({ email: u.email, user: 'skipped', owner: 'n/a', notes: [u.reason] }); continue }
267
+ const person = people.get(u.email)
268
+ const row = { email: u.email, user: u.action === 'member' ? 'linked' : person.user, suid: person.suid, member: false, owner: 'n/a', notes: [...person.notes] }
269
+ const principalError = person.suid && org !== 'failed' && org !== 'skipped' ? await ensurePrincipal(u.email, person.suid) : null
270
+ if (principalError) row.notes.push(principalError)
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 })
273
+ row.member = member.status === 201
274
+ if (!row.member) row.notes.push(`member add failed (${member.status}): ${member.message}`)
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 })
277
+ row.owner = owner.status === 201 ? 'granted' : owner.status === 409 ? 'exists' : 'failed'
278
+ if (row.owner === 'granted') summary.ownersGranted++
279
+ if (row.owner === 'exists') row.notes.push('the org already has an owner; grant more owners in the product')
280
+ if (row.owner === 'failed') row.notes.push(`owner bootstrap failed (${owner.status}): ${owner.message}`)
281
+ } else if (u.grant !== 'owner') {
282
+ row.notes.push(`${u.role} not granted by import; grant it in the product`)
283
+ }
284
+ }
285
+ users.push(row)
286
+ }
287
+ accounts.push({ id: a.id, name: a.name, org, users })
288
+ }
289
+ return { startedAt, finishedAt: now().toISOString(), target: plan.target, job, accounts, summary }
290
+ }
291
+
292
+ module.exports = { planImport, applyImport, formatPlan, toCsv, parseCsv, csvRow }
@@ -0,0 +1,90 @@
1
+ // The users-import manifest: provider-neutral users grouped into accounts (each becomes an org), with the role each
2
+ // person gets. Written by `users export`, reviewed by a human, read by `users import`. Holds personal data, no secrets.
3
+ 'use strict'
4
+
5
+ const MANIFEST_VERSION = 1
6
+ /** The logical role for the product catalog's owner role (resolved server-side by bootstrap-owner). */
7
+ const OWNER = 'owner'
8
+ const MAX_ID_LENGTH = 256
9
+ const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
10
+
11
+ /** Default role hook: everyone owns their account. */
12
+ function defaultRole() {
13
+ return OWNER
14
+ }
15
+
16
+ /** @param {{ givenName?: string | null, familyName?: string | null, name?: string | null, email?: string | null }} u */
17
+ function displayName(u) {
18
+ const full = [u.givenName, u.familyName].filter(Boolean).join(' ')
19
+ return full || u.name || u.email || null
20
+ }
21
+
22
+ /**
23
+ * Group exported users into accounts. A user without an account id gets an account of their own (id = their source id).
24
+ * @param {{ provider: string, source: object, users: Iterable<object> | AsyncIterable<object>,
25
+ * roleFor?: (ctx: { user: object, account: object, index: number }) => string, now?: Date }} input
26
+ */
27
+ async function buildManifest({ provider, source, users, roleFor = defaultRole, now = new Date() }) {
28
+ const accounts = new Map()
29
+ for await (const u of users) {
30
+ const id = u.accountId || u.sourceId
31
+ if (!accounts.has(id)) accounts.set(id, { sourceAccountId: id, id, name: u.accountName || null, users: [] })
32
+ const account = accounts.get(id)
33
+ if (!account.name && u.accountName) account.name = u.accountName
34
+ account.users.push({
35
+ sourceId: u.sourceId,
36
+ email: u.email,
37
+ emailVerified: u.emailVerified,
38
+ givenName: u.givenName,
39
+ familyName: u.familyName,
40
+ name: u.name,
41
+ phone: u.phone,
42
+ enabled: u.enabled,
43
+ status: u.status,
44
+ })
45
+ }
46
+ for (const account of accounts.values()) {
47
+ if (!account.name) account.name = displayName(account.users[0])
48
+ account.users.forEach((user, index) => { user.role = roleFor({ user, account, index }) })
49
+ }
50
+ return {
51
+ version: MANIFEST_VERSION,
52
+ source: { provider, ...source, exportedAt: now.toISOString() },
53
+ accounts: [...accounts.values()],
54
+ }
55
+ }
56
+
57
+ /** @param {string} id @returns {string | null} why the id can't be an org id */
58
+ function orgIdProblem(id) {
59
+ if (typeof id !== 'string' || !id.trim()) return 'is empty'
60
+ if (id.length > MAX_ID_LENGTH) return `exceeds ${MAX_ID_LENGTH} characters`
61
+ if (/[\x00-\x1f\x7f]/.test(id)) return 'contains control characters'
62
+ if (id.includes('#')) return 'contains "#"'
63
+ return null
64
+ }
65
+
66
+ /**
67
+ * Structural checks before an import. A person listed in several accounts is fine: one user, a member of each.
68
+ * @param {any} m
69
+ * @returns {string[]}
70
+ */
71
+ function validateManifest(m) {
72
+ if (!m || m.version !== MANIFEST_VERSION) return [`unsupported manifest version ${m && m.version} (expected ${MANIFEST_VERSION})`]
73
+ if (!Array.isArray(m.accounts)) return ['accounts must be an array']
74
+ const errors = []
75
+ const ids = new Set()
76
+ m.accounts.forEach((a, i) => {
77
+ const problem = orgIdProblem(a.id)
78
+ if (problem) errors.push(`accounts[${i}].id "${a.id}" ${problem}`)
79
+ if (ids.has(a.id)) errors.push(`accounts[${i}].id "${a.id}" is listed twice`)
80
+ ids.add(a.id)
81
+ if (!Array.isArray(a.users) || !a.users.length) errors.push(`accounts[${i}] has no users`)
82
+ ;(a.users || []).forEach((u, j) => {
83
+ if (!EMAIL_RE.test(u.email || '')) errors.push(`accounts[${i}].users[${j}].email "${u.email}" is not an email address`)
84
+ if (typeof u.role !== 'string' || !u.role) errors.push(`accounts[${i}].users[${j}].role is required`)
85
+ })
86
+ })
87
+ return errors
88
+ }
89
+
90
+ module.exports = { MANIFEST_VERSION, OWNER, buildManifest, validateManifest, displayName, defaultRole }
@@ -0,0 +1,61 @@
1
+ // Cognito source provider for `saaslayer users export`: lists a user pool's users with your own AWS credentials
2
+ // (via the AWS CLI) and normalizes them. Read-only, and nothing secret — Cognito never exports password hashes.
3
+ 'use strict'
4
+
5
+ const name = 'cognito'
6
+
7
+ /** Flags this provider reads (kebab-case on the CLI, camelCase in `opts`). */
8
+ const options = {
9
+ 'user-pool-id': 'the source user pool id (required)',
10
+ region: 'the source pool region (required)',
11
+ profile: 'AWS profile with read access to the source pool',
12
+ 'account-attribute': 'user attribute naming the account a user belongs to (e.g. custom:orgId); default: one account per user',
13
+ 'account-name-attribute': 'user attribute holding the account display name (e.g. custom:company)',
14
+ }
15
+
16
+ /** @param {Array<{ Name: string, Value: string }>} list @param {string | undefined} attr */
17
+ function read(list, attr) {
18
+ if (!attr) return null
19
+ const found = (list || []).find((a) => a.Name === attr)
20
+ return found && typeof found.Value === 'string' && found.Value.trim() ? found.Value.trim() : null
21
+ }
22
+
23
+ /**
24
+ * One Cognito user → the provider-neutral user shape every provider yields.
25
+ * @param {{ Username: string, Enabled?: boolean, UserStatus?: string, Attributes?: Array<{ Name: string, Value: string }> }} user
26
+ * @param {{ accountAttribute?: string, accountNameAttribute?: string }} opts
27
+ */
28
+ function normalizeCognitoUser(user, opts = {}) {
29
+ const a = user.Attributes || []
30
+ const email = read(a, 'email')
31
+ return {
32
+ sourceId: read(a, 'sub') || user.Username,
33
+ username: user.Username,
34
+ email: email ? email.toLowerCase() : null,
35
+ emailVerified: read(a, 'email_verified') === 'true',
36
+ givenName: read(a, 'given_name'),
37
+ familyName: read(a, 'family_name'),
38
+ name: read(a, 'name'),
39
+ phone: read(a, 'phone_number'),
40
+ enabled: user.Enabled !== false,
41
+ status: user.UserStatus || null,
42
+ accountId: read(a, opts.accountAttribute),
43
+ accountName: read(a, opts.accountNameAttribute),
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Every user in the pool, normalized. The AWS CLI pages through ListUsers itself.
49
+ * @param {{ userPoolId?: string, region?: string, profile?: string, accountAttribute?: string, accountNameAttribute?: string }} opts
50
+ * @param {{ exec: (cmd: string, args: string[]) => string }} deps
51
+ */
52
+ async function* exportUsers(opts, { exec }) {
53
+ if (!opts.userPoolId) throw new Error('cognito provider: --user-pool-id is required')
54
+ if (!opts.region) throw new Error('cognito provider: --region is required')
55
+ const args = ['cognito-idp', 'list-users', '--user-pool-id', opts.userPoolId, '--output', 'json', '--region', opts.region]
56
+ if (opts.profile) args.push('--profile', opts.profile)
57
+ const out = JSON.parse(exec('aws', args))
58
+ for (const user of out.Users || []) yield normalizeCognitoUser(user, opts)
59
+ }
60
+
61
+ module.exports = { name, options, export: exportUsers, normalizeCognitoUser }
@@ -0,0 +1,24 @@
1
+ // Source-provider registry for `saaslayer users export`: each provider reads users from another identity system
2
+ // and yields the provider-neutral user shape (see docs/users-import.md to add one, e.g. auth0 or clerk).
3
+ 'use strict'
4
+
5
+ const PROVIDERS = {
6
+ cognito: require('./cognito'),
7
+ }
8
+
9
+ /** @returns {string[]} */
10
+ function providerNames() {
11
+ return Object.keys(PROVIDERS)
12
+ }
13
+
14
+ /**
15
+ * @param {string} name
16
+ * @returns {{ name: string, options: Record<string, string>, export: (opts: object, deps: object) => AsyncIterable<object> }}
17
+ */
18
+ function getProvider(name) {
19
+ const provider = PROVIDERS[name]
20
+ if (!provider) throw new Error(`unknown provider "${name}" (available: ${providerNames().join(', ')})`)
21
+ return provider
22
+ }
23
+
24
+ module.exports = { getProvider, providerNames }
@@ -0,0 +1,109 @@
1
+ # SaaSLayer per-region foundation. Installed once per account+REGION, alongside the account-global
2
+ # saaslayer-foundation (IAM) stack; home for every region-bound foundation resource.
3
+ #
4
+ # SOURCE OF TRUTH — edit THIS file only. packages/cli/templates/saaslayer-foundation-region.yml is an
5
+ # auto-synced copy (run `npm run sync-template` from packages/cli). `npm test` fails on drift.
6
+ #
7
+ # WHY A SEPARATE STACK: saaslayer-foundation holds IAM (roles, trust, permission boundary), which is
8
+ # account-global — a role cannot be created twice, so that stack bootstraps ONCE PER ACCOUNT and cannot
9
+ # deploy per-region. S3 (and other region-bound resources) must exist per account+region. The presence
10
+ # of a region in the stack name IS the scope signal: `saaslayer-foundation` (no region) is account-global,
11
+ # `saaslayer-foundation-<region>` is that region's foundation.
12
+ #
13
+ # FIRST OCCUPANT — the shared deployment-artifact bucket. Every SaaSLayer service Serverless-deploys its
14
+ # packaged template + lambda zips into this ONE bucket (via provider.deploymentBucket), replacing the
15
+ # per-stack *serverlessdeploymentbucket* each deploy would otherwise auto-create. Beyond "fewer buckets"
16
+ # it is the deployment-artifact spine that rollback, provenance, supply-chain scanning, and audit hang off.
17
+ # Likely future occupants (not built yet — this stack is designed to hold them): a per-region KMS key, an
18
+ # access-log bucket, an ops-alert SNS topic, deploy-notification queues, VPC endpoints.
19
+ AWSTemplateFormatVersion: '2010-09-09'
20
+ Description: >-
21
+ SaaSLayer per-region foundation stack: region-bound resources for a SaaSLayer host account, starting
22
+ with the shared deployment-artifact bucket every SaaSLayer service deploys into. Installed once per
23
+ account+region, after the account-global saaslayer-foundation (IAM) stack.
24
+
25
+ Parameters:
26
+ ArtifactsBucketName:
27
+ Type: String
28
+ AllowedPattern: '^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$'
29
+ Description: >-
30
+ Name of the shared deployment-artifact bucket. Passed in (not derived here) because the name is
31
+ sl-artifacts-<opaqueAccountToken>-<regionCode> where opaqueAccountToken = sha256(accountId|'artifacts')
32
+ — CloudFormation cannot hash, so the deployer derives it (artifactsBucketName in @saaslayer/config /
33
+ deployer refs.ts) and passes it, guaranteeing the bucket and the injected SERVERLESS_DEPLOYMENT_BUCKET
34
+ agree byte-for-byte. Opaque (no raw account id) so a globally-probeable S3 name never confirms the
35
+ account is SaaSLayer-managed.
36
+
37
+ Mappings:
38
+ # Per-region foundation template version (semver). BUMP on every change so ops can tell which regional
39
+ # bootstrap an account+region runs (surfaced via the FoundationRegionVersion Output). Bump rules mirror
40
+ # saaslayer-foundation: major = breaking change (resource replaced/removed), minor = additive, patch = docs.
41
+ Meta:
42
+ FoundationRegion:
43
+ Version: '1.0.0'
44
+
45
+ Resources:
46
+ # Shared deployment-artifact bucket. Serverless namespaces every deploy under
47
+ # <deploymentPrefix>/<service>/<stage>/<timestamp>/ WITHIN the bucket, so many stacks share it safely;
48
+ # the deployer sets deploymentPrefix=<deploymentId>/<serviceInstance> for per-instance lifecycle + IAM
49
+ # scoping. Versioned (immutable rollback source), SSE-S3 encrypted, private, TLS-and-SSE enforced by the
50
+ # bucket policy below, and age-swept by a lifecycle rule that complements Serverless's keep-last-N.
51
+ DeploymentArtifactBucket:
52
+ Type: AWS::S3::Bucket
53
+ Properties:
54
+ BucketName: !Ref ArtifactsBucketName
55
+ PublicAccessBlockConfiguration:
56
+ BlockPublicAcls: true
57
+ BlockPublicPolicy: true
58
+ IgnorePublicAcls: true
59
+ RestrictPublicBuckets: true
60
+ BucketEncryption:
61
+ ServerSideEncryptionConfiguration:
62
+ - ServerSideEncryptionByDefault:
63
+ SSEAlgorithm: AES256
64
+ VersioningConfiguration:
65
+ Status: Enabled
66
+ LifecycleConfiguration:
67
+ Rules:
68
+ # Age-cap: sweep artifacts older than 90 days regardless of count (Serverless's keep-last-N is a
69
+ # count-cap; together, recent deploys stay for rollback, ancient ones go). Expire old noncurrent
70
+ # versions quickly so versioning does not accumulate unbounded, and clean up failed multipart uploads.
71
+ - Id: expire-old-artifacts
72
+ Status: Enabled
73
+ ExpirationInDays: 90
74
+ NoncurrentVersionExpiration:
75
+ NoncurrentDays: 30
76
+ AbortIncompleteMultipartUpload:
77
+ DaysAfterInitiation: 7
78
+
79
+ # Deny anything not over TLS. Encryption at rest is guaranteed by the bucket's DEFAULT SSE-S3
80
+ # (BucketEncryption above) — every object is encrypted regardless of the request. We deliberately do NOT
81
+ # also deny uploads lacking an explicit x-amz-server-side-encryption header: standard S3 clients (osls /
82
+ # Serverless Framework uploading deploy artifacts) don't send it, so that deny blocks legitimate deploys
83
+ # while adding no real protection (default encryption already applies). Public access is blocked by the
84
+ # account + bucket PublicAccessBlock above.
85
+ DeploymentArtifactBucketPolicy:
86
+ Type: AWS::S3::BucketPolicy
87
+ Properties:
88
+ Bucket: !Ref DeploymentArtifactBucket
89
+ PolicyDocument:
90
+ Version: '2012-10-17'
91
+ Statement:
92
+ - Sid: DenyInsecureTransport
93
+ Effect: Deny
94
+ Principal: '*'
95
+ Action: 's3:*'
96
+ Resource:
97
+ - !GetAtt DeploymentArtifactBucket.Arn
98
+ - !Sub '${DeploymentArtifactBucket.Arn}/*'
99
+ Condition:
100
+ Bool:
101
+ aws:SecureTransport: 'false'
102
+
103
+ Outputs:
104
+ ArtifactsBucketName:
105
+ Description: Shared deployment-artifact bucket every SaaSLayer service in this account+region deploys into.
106
+ Value: !Ref DeploymentArtifactBucket
107
+ FoundationRegionVersion:
108
+ Description: Version of this per-region foundation template installed in the account+region.
109
+ Value: !FindInMap [Meta, FoundationRegion, Version]