saaslayer 0.0.2 → 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 (51) hide show
  1. package/README.md +195 -8
  2. package/bin/saaslayer.js +454 -38
  3. package/package.json +19 -4
  4. package/src/api-client.js +91 -0
  5. package/src/aws-sigv4.js +47 -0
  6. package/src/commands/access-admins.js +73 -0
  7. package/src/commands/accounts.js +54 -0
  8. package/src/commands/activity.js +33 -0
  9. package/src/commands/aws.js +132 -0
  10. package/src/commands/catalog.js +246 -0
  11. package/src/commands/context.js +64 -0
  12. package/src/commands/deploy.js +118 -0
  13. package/src/commands/first-admin.js +42 -0
  14. package/src/commands/foundation.js +405 -0
  15. package/src/commands/lifecycle.js +124 -0
  16. package/src/commands/login.js +261 -0
  17. package/src/commands/machine-trust.js +96 -0
  18. package/src/commands/migrate.js +290 -0
  19. package/src/commands/operations.js +140 -0
  20. package/src/commands/orgs.js +81 -0
  21. package/src/commands/permissions-inspect.js +228 -0
  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 +22 -0
  26. package/src/commands/users.js +269 -0
  27. package/src/config.js +49 -0
  28. package/src/context-store.js +37 -0
  29. package/src/credentials.js +285 -0
  30. package/src/deployment-api-auth.js +61 -0
  31. package/src/deployment-auth.js +38 -0
  32. package/src/deployments.js +26 -0
  33. package/src/discovery.js +66 -0
  34. package/src/env-compare.js +143 -0
  35. package/src/foundation-template.js +57 -0
  36. package/src/iam-session.js +67 -0
  37. package/src/migrations-lib.js +15 -0
  38. package/src/module-catalog.js +66 -0
  39. package/src/permissions-request.js +43 -0
  40. package/src/prompt.js +19 -0
  41. package/src/release-manifest.js +334 -0
  42. package/src/scope.js +114 -0
  43. package/src/settings.js +272 -0
  44. package/src/users-api.js +165 -0
  45. package/src/users-import/ids.js +24 -0
  46. package/src/users-import/import.js +292 -0
  47. package/src/users-import/manifest.js +90 -0
  48. package/src/users-import/providers/cognito.js +61 -0
  49. package/src/users-import/providers/index.js +24 -0
  50. package/templates/saaslayer-foundation-region.yml +109 -0
  51. package/templates/{host-account.yml → saaslayer-foundation.yml} +381 -87
package/src/scope.js ADDED
@@ -0,0 +1,114 @@
1
+ // The scope a command acts on (org, project, deploy env) with where each value came from, the `scope:` line every
2
+ // scoped command prints, and the empty-result hint that lists the caller's projects that do have deployments.
3
+ 'use strict'
4
+ const context = require('./context-store')
5
+ const { apiCall } = require('./api-client')
6
+
7
+ /**
8
+ * @typedef {{ value: string|null, source: 'flag'|'context'|'default'|null }} ScopeValue
9
+ * @typedef {{ org: ScopeValue, project: ScopeValue & { kind: string }, env: ScopeValue }} Scope
10
+ */
11
+
12
+ /**
13
+ * A project is an RBAC tenant (tnt_ TypeID) and its id is the deployer customerId. Deployments created before
14
+ * projects existed carry a bare customer id. Both select the same deployments; the label says which one was given.
15
+ * @param {string} id
16
+ * @returns {'project id'|'customer id'}
17
+ */
18
+ function projectIdKind(id) {
19
+ return /^tnt_/.test(String(id)) ? 'project id' : 'customer id'
20
+ }
21
+
22
+ /**
23
+ * @param {unknown} flagValue
24
+ * @param {string} contextKey
25
+ * @returns {ScopeValue}
26
+ */
27
+ function fromFlagOrContext(flagValue, contextKey) {
28
+ if (typeof flagValue === 'string' && flagValue) return { value: flagValue, source: 'flag' }
29
+ const stored = context.get(contextKey)
30
+ return stored ? { value: stored, source: 'context' } : { value: null, source: null }
31
+ }
32
+
33
+ /**
34
+ * Resolve the org, project and deploy env for a scoped command. Throws when no project is selected.
35
+ * @param {object} flags
36
+ * @param {{ env: string }} defaults the env used when --env is absent ('all' for commands that span every env)
37
+ * @returns {Scope}
38
+ */
39
+ function resolveScope(flags, defaults) {
40
+ const project = fromFlagOrContext(flags.project, 'project')
41
+ if (!project.value) throw new Error('no project selected — run `saaslayer project use <id>` or pass --project')
42
+ return {
43
+ org: fromFlagOrContext(flags.org, 'org'),
44
+ project: { ...project, kind: projectIdKind(project.value) },
45
+ env: typeof flags.env === 'string' && flags.env ? { value: flags.env, source: 'flag' } : { value: defaults.env, source: 'default' },
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @param {Scope} scope
51
+ * @returns {string}
52
+ */
53
+ function formatScopeLine(scope) {
54
+ const sources = ['org', 'project', 'env'].filter((k) => scope[k].source).map((k) => `${k}=${scope[k].source}`)
55
+ return `scope: org=${scope.org.value || '—'} project=${scope.project.value} (${scope.project.kind}) env=${scope.env.value} (from: ${sources.join(' ')})`
56
+ }
57
+
58
+ /**
59
+ * Print the scope line on stderr so stdout stays the command's result. --json suppresses it.
60
+ * @param {Scope} scope
61
+ * @param {object} flags
62
+ */
63
+ function printScope(scope, flags) {
64
+ if (flags.json) return
65
+ console.error(formatScopeLine(scope))
66
+ }
67
+
68
+ /**
69
+ * Group the caller's live deployments by project/customer id.
70
+ * @param {Array<{ id: string, attributes?: Record<string, any> }>} rows GET /api/deployments data
71
+ * @returns {Array<{ id: string, orgId: string|null, count: number, environments: string[] }>}
72
+ */
73
+ function deployedProjects(rows) {
74
+ /** @type {Map<string, { id: string, orgId: string|null, count: number, environments: string[] }>} */
75
+ const byId = new Map()
76
+ for (const row of rows) {
77
+ const a = row.attributes || {}
78
+ if (!a.customerId || a.status === 'DESTROYED') continue
79
+ const entry = byId.get(a.customerId) || { id: a.customerId, orgId: a.orgId || null, count: 0, environments: [] }
80
+ entry.count++
81
+ if (a.environment && !entry.environments.includes(a.environment)) entry.environments.push(a.environment)
82
+ byId.set(a.customerId, entry)
83
+ }
84
+ return [...byId.values()]
85
+ }
86
+
87
+ /**
88
+ * Hint lines listing the projects with deployments, other than the one that came back empty.
89
+ * @param {ReturnType<typeof deployedProjects>} projects
90
+ * @param {string} emptyProjectId
91
+ * @returns {string[]}
92
+ */
93
+ function formatDeployedProjects(projects, emptyProjectId) {
94
+ const others = projects.filter((p) => p.id !== emptyProjectId)
95
+ if (!others.length) return ['you have no deployments in any project you can see — deploy with `saaslayer deploy`']
96
+ return [
97
+ 'projects you can see that have deployments:',
98
+ ...others.map((p) => ` ${p.id} (${projectIdKind(p.id)}) org ${p.orgId || '—'} ${p.count} deployment(s): ${p.environments.join(', ')}`),
99
+ 'retry with: saaslayer status --project <id> (or select it: saaslayer project use <id>)',
100
+ ]
101
+ }
102
+
103
+ /**
104
+ * Fetch the caller's deployments and build the empty-result hint.
105
+ * @param {Scope} scope
106
+ * @param {object} flags
107
+ * @returns {Promise<string[]>}
108
+ */
109
+ async function deployedProjectsHint(scope, flags) {
110
+ const doc = await apiCall('GET', '/api/deployments', undefined, flags)
111
+ return formatDeployedProjects(deployedProjects(doc.data || []), scope.project.value)
112
+ }
113
+
114
+ module.exports = { projectIdKind, resolveScope, formatScopeLine, printScope, deployedProjects, formatDeployedProjects, deployedProjectsHint }
@@ -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 }
@@ -0,0 +1,24 @@
1
+ // The platform user-id minter (@saaslayer/ids' bare 26-char UUIDv7 TypeID suffix) for imported users' custom:suid —
2
+ // the same generator the user-service uses. Vendored into the published CLI; the monorepo source is the fallback.
3
+ 'use strict'
4
+ const path = require('path')
5
+
6
+ // The monorepo source, for running the CLI from a checkout before vendor/ is synced. Resolved at runtime because it
7
+ // is never shipped: the published package carries vendor/ids (synced on prepack).
8
+ const MONOREPO_IDS = path.join(__dirname, '../../../ids/src')
9
+
10
+ function loadIds() {
11
+ try {
12
+ return require('../../vendor/ids')
13
+ } catch (err) {
14
+ if (err && err.code !== 'MODULE_NOT_FOUND') throw err
15
+ return require(MONOREPO_IDS)
16
+ }
17
+ }
18
+
19
+ /** @returns {string} a new stable SaaSLayer user id */
20
+ function mintSuid() {
21
+ return loadIds().generateTypeIdSuffix()
22
+ }
23
+
24
+ module.exports = { mintSuid }