saaslayer 0.2.0 → 0.4.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 (68) hide show
  1. package/README.md +132 -16
  2. package/bin/saaslayer.js +387 -61
  3. package/package.json +3 -2
  4. package/src/api-client.js +37 -1
  5. package/src/aws-sigv4.js +74 -26
  6. package/src/cognito-user-api.js +80 -0
  7. package/src/commands/access-admins.js +2 -2
  8. package/src/commands/account-email.js +43 -0
  9. package/src/commands/admin-allowlist.js +65 -0
  10. package/src/commands/api-keys.js +83 -0
  11. package/src/commands/audit.js +77 -0
  12. package/src/commands/aws.js +355 -82
  13. package/src/commands/binding-handoff.js +174 -0
  14. package/src/commands/bindings.js +111 -0
  15. package/src/commands/catalog.js +30 -3
  16. package/src/commands/deploy.js +33 -10
  17. package/src/commands/env-export.js +58 -0
  18. package/src/commands/first-admin.js +15 -4
  19. package/src/commands/foundation.js +75 -117
  20. package/src/commands/hooks.js +271 -0
  21. package/src/commands/integration-credentials.js +1 -1
  22. package/src/commands/lifecycle.js +149 -24
  23. package/src/commands/login-domain.js +259 -0
  24. package/src/commands/login.js +53 -16
  25. package/src/commands/org-members.js +109 -0
  26. package/src/commands/permission-orgs.js +80 -0
  27. package/src/commands/release-manifest.js +17 -8
  28. package/src/commands/service-principals.js +42 -5
  29. package/src/commands/settings.js +21 -5
  30. package/src/commands/sms-registration.js +182 -0
  31. package/src/commands/sms.js +178 -0
  32. package/src/commands/social.js +265 -0
  33. package/src/commands/support-staff.js +72 -0
  34. package/src/commands/trust-policies.js +172 -0
  35. package/src/commands/users-management.js +2 -20
  36. package/src/commands/users.js +56 -11
  37. package/src/commands/versions.js +61 -0
  38. package/src/connection-proof.js +41 -0
  39. package/src/deployment-api-auth.js +166 -8
  40. package/src/deployments.js +1 -1
  41. package/src/foundation-change-set.js +180 -0
  42. package/src/foundation-home.js +121 -0
  43. package/src/foundation-template.js +51 -10
  44. package/src/foundation-trust-write.js +379 -0
  45. package/src/iam-session.js +14 -8
  46. package/src/login-domain.js +139 -0
  47. package/src/login-methods.js +118 -0
  48. package/src/module-catalog.js +3 -2
  49. package/src/permissions-request.js +15 -9
  50. package/src/release-manifest.js +11 -4
  51. package/src/scope.js +3 -1
  52. package/src/settings.js +85 -13
  53. package/src/sms/number.js +37 -0
  54. package/src/sms/registration-fields.js +167 -0
  55. package/src/sms/registration-validate.js +151 -0
  56. package/src/sms/registration.js +216 -0
  57. package/src/sms/release.js +55 -0
  58. package/src/sms/scope.js +86 -0
  59. package/src/sms/status.js +181 -0
  60. package/src/ssm-api.js +31 -0
  61. package/src/trust-entries.js +350 -0
  62. package/src/user-service-instance.js +27 -0
  63. package/src/users-api.js +55 -8
  64. package/src/users-import/checkpoint.js +76 -0
  65. package/src/users-import/import.js +233 -24
  66. package/src/versions.js +80 -0
  67. package/templates/saaslayer-foundation-region.yml +45 -1
  68. package/templates/saaslayer-foundation.yml +747 -296
@@ -0,0 +1,86 @@
1
+ // The account and region an `saaslayer sms …` command acts on (plan §3): resolved by the control plane from the project's
2
+ // deployment for --env, else its connected account; printed under the scope line, then the cloud-prem checks.
3
+ 'use strict'
4
+ const { jsonApiCall } = require('../api-client')
5
+ const { resolveScope, formatScopeLine } = require('../scope')
6
+ const { awsRunner } = require('../foundation-change-set')
7
+
8
+ /** v1 has one sender per account and region (plan §5b); commands take a sender name internally, no flag yet. */
9
+ const DEFAULT_SMS_SENDER = 'default'
10
+
11
+ /**
12
+ * @typedef {{ accountId: string, region: string, source: 'deployment'|'connected-account', deploymentId: string|null,
13
+ * accountOwnership: string, dedicatedAccount: boolean, protectedDeployments: boolean, env: string, project: string,
14
+ * sender: string, scope: import('../scope').Scope }} SmsTarget
15
+ * @typedef {{ api?: typeof jsonApiCall, log?: (...a: unknown[]) => void, sender?: string }} ScopeDeps
16
+ */
17
+
18
+ /**
19
+ * Resolve the target account and region of `--env` (and `--region` when the env spans several). Prints the scope line and
20
+ * the target line on stderr (--json suppresses both).
21
+ * @param {Record<string, any>} flags
22
+ * @param {ScopeDeps} [deps]
23
+ * @returns {Promise<SmsTarget>}
24
+ */
25
+ async function resolveSmsTarget(flags, { api = jsonApiCall, log = console.error, sender = DEFAULT_SMS_SENDER } = {}) {
26
+ if (typeof flags.env !== 'string' || !flags.env) throw new Error('--env is required (the environment whose account and region send the SMS, e.g. --env dev)')
27
+ const scope = resolveScope(flags, { env: flags.env })
28
+ if (!flags.json) log(formatScopeLine(scope))
29
+ const project = String(scope.project.value)
30
+ const query = new URLSearchParams({ environment: flags.env, ...(typeof flags.region === 'string' ? { region: flags.region } : {}) })
31
+ const doc = await api('GET', `/api/projects/${encodeURIComponent(project)}/sms-target?${query}`, undefined, flags)
32
+ const a = doc.data.attributes
33
+ /** @type {SmsTarget} */
34
+ const target = { ...a, env: flags.env, project, sender, scope }
35
+ if (!flags.json) log(`target: account=${a.accountId} region=${a.region} (from: ${a.source === 'deployment' ? `${flags.env} deployment ${a.deploymentId}` : 'connected account'})`)
36
+ return target
37
+ }
38
+
39
+ /**
40
+ * The AWS-calling `sms` commands run with the customer's own credentials (cloud-prem); anything else is refused. A shared
41
+ * hosted account can never carry a customer's brand (D7); a dedicated one waits on the control plane making these calls
42
+ * (monorepo-aagbc).
43
+ * @param {SmsTarget} target @param {string} command
44
+ */
45
+ function refuseHostedAccount(target, command) {
46
+ if (target.accountOwnership === 'cloud-prem') return
47
+ if (target.accountOwnership === 'hosted' && !target.dedicatedAccount) {
48
+ throw new Error(`${command}: account ${target.accountId}: sms.shared-account-unsupported: phone SMS needs a dedicated account: this is a shared hosted account, and one account-wide sending number cannot carry each customer's registered brand; deploy phone sign-in to a dedicated hosted account or to your own AWS account`)
49
+ }
50
+ throw new Error(`${command}: account ${target.accountId} is a SaaSLayer-hosted account; ${command} works on your own AWS account (cloud-prem) only for now — hosted accounts are not supported yet (the control plane would make these AWS calls there)`)
51
+ }
52
+
53
+ /**
54
+ * Cloud-prem: the caller's AWS credentials must be for the target account (the account check `aws connect` makes).
55
+ * @param {import('../foundation-change-set').AwsJson} aws @param {SmsTarget} target
56
+ * @returns {string} the caller's ARN
57
+ */
58
+ function checkCallerAccount(aws, target) {
59
+ const identity = aws(['sts', 'get-caller-identity'])
60
+ if (identity.Account !== target.accountId) {
61
+ throw new Error(`your AWS credentials are for account ${identity.Account}, not ${target.accountId} (the ${target.env} ${target.source === 'deployment' ? 'deployment' : 'connected'} account); switch credentials (or pass --profile) and retry`)
62
+ }
63
+ return String(identity.Arn)
64
+ }
65
+
66
+ /**
67
+ * The target of an AWS-calling `sms` command after the cloud-prem checks (not hosted, the caller's credentials are for
68
+ * the target account), with an `aws` CLI runner for its region and --profile.
69
+ * @param {Record<string, any>} flags @param {string} command
70
+ * @param {{ api?: typeof jsonApiCall, exec: (cmd: string, args: string[]) => string, log?: (...a: unknown[]) => void }} deps
71
+ * @returns {Promise<{ target: SmsTarget, aws: import('../foundation-change-set').AwsJson }>}
72
+ */
73
+ async function cloudPremTarget(flags, command, { api, exec, log }) {
74
+ const target = await resolveSmsTarget(flags, { api, log })
75
+ refuseHostedAccount(target, command)
76
+ const aws = awsRunner(exec, { region: target.region, profile: flags.profile })
77
+ checkCallerAccount(aws, target)
78
+ return { target, aws }
79
+ }
80
+
81
+ /** The control-plane path of the SMS release record of the target's account, region and sender. @param {SmsTarget} t */
82
+ function smsReleasePath(t) {
83
+ return `/api/accounts/${t.accountId}/regions/${encodeURIComponent(t.region)}/sms-senders/${encodeURIComponent(t.sender)}/release`
84
+ }
85
+
86
+ module.exports = { DEFAULT_SMS_SENDER, resolveSmsTarget, refuseHostedAccount, checkCallerAccount, cloudPremTarget, smsReleasePath }
@@ -0,0 +1,181 @@
1
+ // `saaslayer sms status`: what the account's SMS sending setup has (number, registration, tier, spend limit, a release in
2
+ // progress), what is still missing as the deployer's readiness codes (same wording), and the support requests with no API.
3
+ 'use strict'
4
+ const {
5
+ DescribeAccountAttributesCommand, DescribeSpendLimitsCommand, DescribeVerifiedDestinationNumbersCommand,
6
+ } = require('@aws-sdk/client-pinpoint-sms-voice-v2')
7
+ const { PROTECTED_ENVS } = require('../settings')
8
+ const sms = require('./registration')
9
+ const { isUnfinished } = require('./release')
10
+
11
+ /**
12
+ * @typedef {{ code: string, severity: 'refuse'|'pending'|'sandbox', value?: string, guidance: string, next: string }} Finding
13
+ * @typedef {{ kind: 'production-access'|'spend-limit', link: string, values: Record<string, string> }} SupportRequest
14
+ */
15
+
16
+ /** Statuses during which AWS (or a carrier) is reviewing: nothing to do but wait. */
17
+ const IN_REVIEW = ['SUBMITTED', 'AWS_REVIEWING', 'REVIEWING', 'PROVISIONING', 'REQUIRES_AUTHENTICATION']
18
+ const PRODUCTION_ACCESS_LINK = 'https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase'
19
+ const PRICING_LINK = 'https://aws.amazon.com/end-user-messaging/pricing/'
20
+
21
+ /**
22
+ * The deployer's guidance for a readiness code (control-plane/services/deployer-service/src/sms-readiness.ts
23
+ * guidanceFor), so `sms status` and a refused deploy word each step the same; a test renders both and compares them.
24
+ * @param {string} code @param {{ value?: string, isProtected: boolean }} o
25
+ */
26
+ function readinessGuidance(code, { value, isProtected }) {
27
+ switch (code) {
28
+ case 'sms.account-sandbox': return isProtected
29
+ ? 'This account and region are in the SMS sandbox, which delivers only to verified destination numbers; request SMS production access for this region in AWS End User Messaging (AWS reviews the request), then retry'
30
+ : 'Test-only: this account and region are in the SMS sandbox, so SMS reaches only destination numbers verified in AWS End User Messaging; request SMS production access before going live'
31
+ case 'sms.spend-limit-initial': return isProtected
32
+ ? 'The monthly SMS spend limit is still the initial AWS limit; request an SMS spend limit increase for this region in AWS End User Messaging, then retry'
33
+ : 'Test-only: the monthly SMS spend limit is still the initial AWS limit; request an SMS spend limit increase before going live'
34
+ case 'sms.origination-missing': return `No active origination identity can send SMS to ${value}${value === 'US' ? ' (US needs a toll-free number, 10DLC number or short code)' : ''}; Cognito test-sends an SMS when phone sign-in is set up, so every environment needs one: run \`saaslayer sms setup\`${isProtected ? '' : ' (--simulator for a number that sends to simulator destinations only)'} or obtain one in AWS End User Messaging, then retry`
35
+ case 'sms.registration-incomplete': return `The origination identity for ${value} has a registration that is not complete, and an unregistered number cannot send Cognito's test SMS when phone sign-in is set up; finish it in AWS End User Messaging (carriers review registrations, which can take days or weeks), then retry`
36
+ case 'sms.origination-simulator': return isProtected
37
+ ? 'A simulator number delivers to simulator destinations only, so prod and staging refuse it; set PhoneSmsOriginationIdentity to a registered toll-free number, 10DLC number or short code'
38
+ : 'delivers to simulator destinations only'
39
+ default: return code
40
+ }
41
+ }
42
+
43
+ /**
44
+ * @param {string} code @param {Finding['severity']} severity @param {string|undefined} value @param {boolean} isProtected @param {string} next
45
+ * @returns {Finding}
46
+ */
47
+ function finding(code, severity, value, isProtected, next) {
48
+ return { code, severity, ...(value ? { value } : {}), guidance: readinessGuidance(code, { value, isProtected }), next }
49
+ }
50
+
51
+ /** A registration field's current text or choice. @param {Array<Record<string, any>>} values @param {string} fieldPath */
52
+ function valueOf(values, fieldPath) {
53
+ const v = values.find((x) => x.FieldPath === fieldPath)
54
+ return v ? v.TextValue || (v.SelectChoices && v.SelectChoices[0]) || '' : ''
55
+ }
56
+
57
+ /**
58
+ * Read the account's SMS setup (Describe/List calls only) and classify what is missing.
59
+ * @param {{ target: import('./scope').SmsTarget, arn: string|null, sms: import('./registration').SmsClient,
60
+ * release?: Record<string, any>|null }} o `release`: the release that was in progress, as it is now
61
+ */
62
+ async function smsStatusReport({ target, arn, sms: client, release = null }) {
63
+ const isProtected = PROTECTED_ENVS.has(target.env)
64
+ const outstanding = isProtected ? 'pending' : 'sandbox'
65
+ const env = target.env
66
+ const number = arn ? await sms.describeNumber(client, arn) : null
67
+ const simulator = Boolean(number && number.NumberType === 'SIMULATOR')
68
+ const found = number && !simulator ? (await sms.findRegistration(client, number)).registration : null
69
+
70
+ let deniedReasons = []
71
+ let values = []
72
+ if (found) {
73
+ values = await sms.fieldValues(client, found.RegistrationId, found.CurrentVersionNumber)
74
+ if (found.RegistrationStatus === 'REQUIRES_UPDATES') {
75
+ const denied = await sms.describeVersion(client, found.RegistrationId, found.LatestDeniedVersionNumber || found.CurrentVersionNumber)
76
+ deniedReasons = ((denied && denied.DeniedReasons) || []).map((r) => ({ reason: r.Reason, description: r.ShortDescription || '' }))
77
+ }
78
+ }
79
+ const attributes = (await client.send(new DescribeAccountAttributesCommand({}))).AccountAttributes || []
80
+ const tier = (attributes.find((a) => a.Name === 'ACCOUNT_TIER') || {}).Value || null
81
+ const limit = ((await client.send(new DescribeSpendLimitsCommand({}))).SpendLimits || []).find((l) => l.Name === 'TEXT_MESSAGE_MONTHLY_SPEND_LIMIT')
82
+ const spendLimit = limit ? { enforcedUsd: limit.EnforcedLimit, maxUsd: limit.MaxLimit, overridden: Boolean(limit.Overridden) } : null
83
+ const verified = ((await client.send(new DescribeVerifiedDestinationNumbersCommand({}))).VerifiedDestinationNumbers || []).filter((d) => d.Status === 'VERIFIED').length
84
+
85
+ /** @type {Finding[]} */
86
+ const findings = []
87
+ // No number, or an unregistered one, is pending on every environment: Cognito test-sends when a pool's SMS
88
+ // configuration is set, and only a simulator number sends without a registration (A68).
89
+ if (!number) findings.push(finding('sms.origination-missing', 'pending', 'US', isProtected, `saaslayer sms setup --env ${env}`))
90
+ else if (simulator) findings.push(finding('sms.origination-simulator', isProtected ? 'refuse' : 'sandbox', undefined, isProtected, isProtected ? `saaslayer sms release --env ${env}, then saaslayer sms setup --env ${env}` : 'none for dev; a real number needs saaslayer sms release, then saaslayer sms setup'))
91
+ else if (!found || found.RegistrationStatus !== 'COMPLETE') {
92
+ const reviewing = Boolean(found && IN_REVIEW.includes(found.RegistrationStatus))
93
+ findings.push(finding('sms.registration-incomplete', 'pending', 'US', isProtected, reviewing ? 'wait for AWS\'s review (up to 15 business days)' : `saaslayer sms register --env ${env}`))
94
+ }
95
+ if (tier !== 'PRODUCTION') findings.push(finding('sms.account-sandbox', outstanding, undefined, isProtected, 'file the production-access support request below'))
96
+ if (!spendLimit || !spendLimit.overridden) findings.push(finding('sms.spend-limit-initial', outstanding, undefined, isProtected, 'file the spend-limit request below'))
97
+
98
+ /** @type {SupportRequest[]} */
99
+ const supportRequests = []
100
+ if (tier !== 'PRODUCTION') {
101
+ supportRequests.push({
102
+ kind: 'production-access',
103
+ link: PRODUCTION_ACCESS_LINK,
104
+ values: {
105
+ Service: 'Service Quotas',
106
+ Category: 'AWS End User Messaging SMS (Pinpoint)',
107
+ Region: target.region,
108
+ 'Resource Type': 'General Limits',
109
+ Quota: 'SMS Production Access',
110
+ 'New quota value': '1',
111
+ 'Site or app that sends': valueOf(values, 'companyInfo.website') || '(your website)',
112
+ 'Message type': 'One Time Password',
113
+ Countries: 'United States (US)',
114
+ 'Opt-in': valueOf(values, 'messagingUseCase.optInDescription') || '(how users opt in)',
115
+ 'Message template': valueOf(values, 'messageSamples.messageSample1') || '(your sign-in code message)',
116
+ 'Monthly volume': valueOf(values, 'messagingUseCase.monthlyMessageVolume') || '(expected messages per month)',
117
+ },
118
+ })
119
+ }
120
+ if (!spendLimit || !spendLimit.overridden) {
121
+ supportRequests.push({
122
+ kind: 'spend-limit',
123
+ link: `https://${target.region}.console.aws.amazon.com/servicequotas/home?region=${target.region}`,
124
+ values: {
125
+ Service: 'AWS End User Messaging',
126
+ Quota: 'TextMessageMonthlySpend',
127
+ Region: target.region,
128
+ 'Current value': spendLimit ? `$${spendLimit.enforcedUsd}` : 'unknown',
129
+ 'Increased quota value': `your expected monthly SMS spend in USD: monthly volume × the US toll-free price per message (${PRICING_LINK})`,
130
+ },
131
+ })
132
+ }
133
+
134
+ const registrationComplete = Boolean(found && found.RegistrationStatus === 'COMPLETE')
135
+ return {
136
+ accountId: target.accountId,
137
+ region: target.region,
138
+ env,
139
+ number: number ? { arn: number.PhoneNumberArn, id: number.PhoneNumberId, phoneNumber: number.PhoneNumber || null, status: number.Status || null, type: number.NumberType || null } : null,
140
+ registration: found ? { id: found.RegistrationId, status: found.RegistrationStatus, version: found.CurrentVersionNumber, deniedReasons } : null,
141
+ accountTier: tier,
142
+ spendLimit,
143
+ smsDeliverable: registrationComplete && number.Status === 'ACTIVE' && (tier === 'PRODUCTION' || verified > 0),
144
+ release: release ? { phase: release.phase, phoneNumberArn: release.phoneNumberArn, registrationId: release.registrationId || null, next: isUnfinished(release.phase) ? `saaslayer sms release --env ${env}` : null } : null,
145
+ findings,
146
+ supportRequests,
147
+ }
148
+ }
149
+
150
+ /** @param {Awaited<ReturnType<typeof smsStatusReport>>} r @returns {string[]} */
151
+ function formatSmsStatus(r) {
152
+ const lines = []
153
+ lines.push(r.number ? `Number: ${r.number.phoneNumber || r.number.id} (${r.number.type}, ${r.number.status})` : 'Number: none')
154
+ lines.push(r.registration ? `Registration: ${r.registration.id} ${r.registration.status} (version ${r.registration.version})` : r.number && r.number.type === 'SIMULATOR' ? 'Registration: not needed (simulator number)' : 'Registration: none')
155
+ for (const d of r.registration ? r.registration.deniedReasons : []) lines.push(` ${d.reason}: ${d.description}`)
156
+ lines.push(`Account: ${r.accountTier || 'unknown'}`)
157
+ lines.push(r.spendLimit ? `Spend limit: $${r.spendLimit.enforcedUsd}/month${r.spendLimit.overridden ? '' : ' (initial AWS limit)'}` : 'Spend limit: unknown')
158
+ lines.push(`SMS deliverable: ${r.smsDeliverable ? 'yes' : 'no'}`)
159
+ if (r.release) {
160
+ lines.push(r.release.next
161
+ ? `Release in progress: ${r.release.phoneNumberArn} (${r.release.phase}); resume it: ${r.release.next}`
162
+ : `Release finished: ${r.release.phoneNumberArn} (${r.release.phase})`)
163
+ }
164
+ lines.push('')
165
+ if (!r.findings.length) lines.push('Nothing missing.')
166
+ else {
167
+ lines.push('Missing:')
168
+ for (const f of r.findings) {
169
+ lines.push(` ${f.code}${f.value ? ` (${f.value})` : ''}: ${f.guidance}`)
170
+ lines.push(` next: ${f.next}`)
171
+ }
172
+ }
173
+ for (const s of r.supportRequests) {
174
+ lines.push('')
175
+ lines.push(s.kind === 'production-access' ? `Request SMS production access (AWS support case): ${s.link}` : `Request a spend limit increase (Service Quotas): ${s.link}`)
176
+ for (const [k, v] of Object.entries(s.values)) lines.push(` ${k}: ${v}`)
177
+ }
178
+ return lines
179
+ }
180
+
181
+ module.exports = { smsStatusReport, formatSmsStatus, readinessGuidance }
package/src/ssm-api.js ADDED
@@ -0,0 +1,31 @@
1
+ // Signed calls to the SSM JSON API with the caller's AWS credentials (no SDK): one action per call, errors named by the
2
+ // AWS error type. Used where the CLI writes or reads SecureString parameters itself.
3
+ 'use strict'
4
+ const { signRequest } = require('./aws-sigv4')
5
+
6
+ /**
7
+ * @param {{ region: string, credentials: () => { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, fetchImpl: typeof fetch }} deps
8
+ * @returns {(action: string, input: Record<string, unknown>) => Promise<any>}
9
+ */
10
+ function ssmApi({ region, credentials, fetchImpl }) {
11
+ const host = `ssm.${region}.amazonaws.com`
12
+ return async function call(action, input) {
13
+ const body = JSON.stringify(input)
14
+ const { headers } = signRequest({
15
+ method: 'POST',
16
+ url: `https://${host}/`,
17
+ body,
18
+ region,
19
+ service: 'ssm',
20
+ credentials: credentials(),
21
+ headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': `AmazonSSM.${action}`, Host: host },
22
+ })
23
+ const res = await fetchImpl(`https://${host}/`, { method: 'POST', headers, body })
24
+ const doc = await res.json().catch(() => ({}))
25
+ if (res.ok) return doc
26
+ const type = String((doc && (doc.__type || doc.code)) || '').split('#').pop()
27
+ throw Object.assign(new Error(`SSM ${action} failed (${res.status}${type ? ` ${type}` : ''})`), { name: type || 'SsmError' })
28
+ }
29
+ }
30
+
31
+ module.exports = { ssmApi }
@@ -0,0 +1,350 @@
1
+ // Per-control-plane trust entries of the account foundation (ADR 0005 §2.1): parse and validate the TrustEntries parameter,
2
+ // merge one control plane's entry, render the entry roles' trust statements, check capacity and patch a foundation template.
3
+ 'use strict'
4
+
5
+ /** The TrustEntries schema version this module reads and writes. */
6
+ const TRUST_ENTRIES_VERSION = 1
7
+ /** Supported capacity: control planes per account, identifiers per control plane (current, plus next during a rotation). */
8
+ const MAX_CONTROL_PLANES = 3
9
+ const MAX_TRUST_IDENTIFIERS = 2
10
+ /** Longest trust identifier accepted; the control plane mints UUIDs. Bounds the worst-case render. */
11
+ const MAX_TRUST_IDENTIFIER_LENGTH = 64
12
+ /** CloudFormation's limit for one String parameter value. */
13
+ const TRUST_ENTRIES_MAX_BYTES = 4096
14
+ /** IAM's default role trust policy size quota, counted without whitespace. */
15
+ const TRUST_POLICY_MAX_CHARS = 2048
16
+
17
+ // A controlPlaneId: lowercase letters, digits and single hyphens, starting with a letter and ending with a letter or digit, 3-50 characters.
18
+ const CONTROL_PLANE_ID = /^[a-z][a-z0-9-]{1,48}[a-z0-9]$/
19
+ const MAX_CONTROL_PLANE_ID_LENGTH = 50
20
+ const ACCOUNT_ID = /^[0-9]{12}$/
21
+ const TRUST_IDENTIFIER = /^[\w+=,.@:/-]{2,64}$/
22
+ const SUPPORT_SESSION_NAME = 'saaslayer-support-*'
23
+
24
+ /** The entry roles carrying rendered trust: their logical id in the foundation template and their caller list key. */
25
+ const ENTRY_ROLES = {
26
+ deploy: { logicalId: 'SaaSLayerDeploymentRole', callers: 'deployCallerArns' },
27
+ support: { logicalId: 'SaaSLayerSupportReadOnlyRole', callers: 'supportCallerArns' },
28
+ }
29
+ /** The SSM parameter resource publishing the authorizers and control-plane ids, and the line before its controlPlanes literal. */
30
+ const AUTHORIZERS_PARAMETER = 'SaaSLayerConnectionAuthorizers'
31
+ const CONTROL_PLANES_LEAD = `- '"],"controlPlanes":'`
32
+
33
+ /**
34
+ * @typedef {{ controlPlaneId: string, principalAccountId: string, trustIdentifiers: string[], v: number,
35
+ * deployCallerArns: string[], supportCallerArns: string[] }} TrustEntry
36
+ * @typedef {{ raw: string, entry: TrustEntry }} ParsedEntry
37
+ * @typedef {'deploy'|'support'} EntryRole
38
+ */
39
+
40
+ /**
41
+ * The control-plane identity role a customer entry role trusts (ADR 0005 D6).
42
+ * @param {string} accountId @param {string} controlPlaneId @param {EntryRole} role
43
+ */
44
+ function identityArn(accountId, controlPlaneId, role) {
45
+ return `arn:aws:iam::${accountId}:role/${controlPlaneId}-${role}`
46
+ }
47
+
48
+ /**
49
+ * One control plane's entry, in the approved key order, with its identity caller ARNs derived.
50
+ * @param {{ controlPlaneId: string, principalAccountId: string, trustIdentifiers: string[] }} input
51
+ * @returns {TrustEntry}
52
+ */
53
+ function controlPlaneEntry({ controlPlaneId, principalAccountId, trustIdentifiers }) {
54
+ const entry = {
55
+ controlPlaneId,
56
+ principalAccountId,
57
+ trustIdentifiers: Array.isArray(trustIdentifiers) ? [...trustIdentifiers] : trustIdentifiers,
58
+ v: TRUST_ENTRIES_VERSION,
59
+ deployCallerArns: [identityArn(principalAccountId, controlPlaneId, 'deploy')],
60
+ supportCallerArns: [identityArn(principalAccountId, controlPlaneId, 'support')],
61
+ }
62
+ validateEntry(entry, 0)
63
+ return entry
64
+ }
65
+
66
+ /**
67
+ * Refuses an entry this reader cannot operate on. Messages name the control plane, never an identifier value.
68
+ * @param {any} entry @param {number} index
69
+ */
70
+ function validateEntry(entry, index) {
71
+ const where = `TrustEntries[${index}]`
72
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw new Error(`${where} is not an object`)
73
+ if (entry.v !== TRUST_ENTRIES_VERSION) {
74
+ throw new Error(`${where} has v ${JSON.stringify(entry.v)}; this CLI reads v ${TRUST_ENTRIES_VERSION} only. Update the saaslayer CLI; nothing was changed.`)
75
+ }
76
+ const id = entry.controlPlaneId
77
+ if (typeof id !== 'string' || !CONTROL_PLANE_ID.test(id) || id.includes('--')) {
78
+ throw new Error(`${where} controlPlaneId must be lowercase letters, digits and single hyphens, starting with a letter and ending with a letter or digit, 3-50 characters`)
79
+ }
80
+ const label = `trust entry ${id}`
81
+ if (typeof entry.principalAccountId !== 'string' || !ACCOUNT_ID.test(entry.principalAccountId)) throw new Error(`${label}: principalAccountId must be a 12-digit AWS account id`)
82
+ const ids = entry.trustIdentifiers
83
+ if (!Array.isArray(ids) || ids.length < 1 || ids.length > MAX_TRUST_IDENTIFIERS) throw new Error(`${label}: needs 1 or 2 trust identifiers (current, plus next during a rotation)`)
84
+ if (!ids.every((value) => typeof value === 'string' && TRUST_IDENTIFIER.test(value))) {
85
+ throw new Error(`${label}: a trust identifier is not 2-${MAX_TRUST_IDENTIFIER_LENGTH} characters of [A-Za-z0-9+=,.@:/_-]`)
86
+ }
87
+ if (new Set(ids).size !== ids.length) throw new Error(`${label}: trust identifiers repeat`)
88
+ for (const role of /** @type {EntryRole[]} */ (['deploy', 'support'])) {
89
+ const key = ENTRY_ROLES[role].callers
90
+ const expected = identityArn(entry.principalAccountId, id, role)
91
+ if (!Array.isArray(entry[key]) || entry[key].length !== 1 || entry[key][0] !== expected) {
92
+ throw new Error(`${label}: ${key} must be exactly the control-plane identity ${expected}`)
93
+ }
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Splits a JSON array's text into the raw text of each top-level element (whitespace around elements trimmed).
99
+ * @param {string} text
100
+ * @returns {string[]}
101
+ */
102
+ function splitArrayElements(text) {
103
+ const body = text.trim()
104
+ const elements = []
105
+ let depth = 0
106
+ let start = 1
107
+ let inString = false
108
+ for (let i = 1; i < body.length - 1; i++) {
109
+ const ch = body[i]
110
+ if (inString) {
111
+ if (ch === '\\') i++
112
+ else if (ch === '"') inString = false
113
+ continue
114
+ }
115
+ if (ch === '"') inString = true
116
+ else if (ch === '{' || ch === '[') depth++
117
+ else if (ch === '}' || ch === ']') depth--
118
+ else if (ch === ',' && depth === 0) {
119
+ elements.push(body.slice(start, i).trim())
120
+ start = i + 1
121
+ }
122
+ }
123
+ const last = body.slice(start, body.length - 1).trim()
124
+ if (last || elements.length) elements.push(last)
125
+ return elements
126
+ }
127
+
128
+ /**
129
+ * Parses a TrustEntries value: every entry validated, each kept with its raw text so another control plane's entry is
130
+ * written back byte-for-byte. An empty value is an empty list.
131
+ * @param {string} text
132
+ * @returns {ParsedEntry[]}
133
+ */
134
+ function parseTrustEntries(text) {
135
+ if (text === undefined || text === null || String(text).trim() === '') return []
136
+ let value
137
+ try {
138
+ value = JSON.parse(text)
139
+ } catch {
140
+ throw new Error('TrustEntries is not valid JSON; nothing was changed')
141
+ }
142
+ if (!Array.isArray(value)) throw new Error('TrustEntries must be a JSON array of trust entries')
143
+ const raws = splitArrayElements(String(text))
144
+ const seen = new Set()
145
+ return value.map((entry, index) => {
146
+ validateEntry(entry, index)
147
+ if (seen.has(entry.controlPlaneId)) throw new Error(`TrustEntries names ${entry.controlPlaneId} more than once`)
148
+ seen.add(entry.controlPlaneId)
149
+ return { raw: raws[index], entry }
150
+ })
151
+ }
152
+
153
+ /**
154
+ * Serializes parsed entries in controlPlaneId order, each from its raw text.
155
+ * @param {ParsedEntry[]} parsed
156
+ */
157
+ function serialize(parsed) {
158
+ const sorted = [...parsed].sort((a, b) => (a.entry.controlPlaneId < b.entry.controlPlaneId ? -1 : a.entry.controlPlaneId > b.entry.controlPlaneId ? 1 : 0))
159
+ return `[${sorted.map((p) => p.raw).join(',')}]`
160
+ }
161
+
162
+ /** @param {unknown} a @param {unknown} b */
163
+ const sameList = (a, b) => JSON.stringify(a) === JSON.stringify(b)
164
+
165
+ /**
166
+ * Merges one control plane's entry into a TrustEntries value, leaving every other entry byte-for-byte. Changing the
167
+ * control plane's account or caller ARNs is an explicit handoff; changing its identifiers is a rotation step.
168
+ * @param {string} text the installed TrustEntries ('' when none)
169
+ * @param {TrustEntry} entry
170
+ * @param {{ handoff?: boolean, identifierChange?: boolean }} [opts]
171
+ * @returns {string}
172
+ */
173
+ function mergeTrustEntry(text, entry, { handoff = false, identifierChange = false } = {}) {
174
+ const parsed = parseTrustEntries(text)
175
+ validateEntry(entry, parsed.length)
176
+ const existing = parsed.find((p) => p.entry.controlPlaneId === entry.controlPlaneId)
177
+ if (existing) {
178
+ const current = existing.entry
179
+ const moved = current.principalAccountId !== entry.principalAccountId || !sameList(current.deployCallerArns, entry.deployCallerArns) ||
180
+ !sameList(current.supportCallerArns, entry.supportCallerArns)
181
+ if (moved && !handoff) {
182
+ throw new Error(`trust entry ${entry.controlPlaneId}: changing its caller account or caller ARNs needs an explicit handoff; nothing was changed`)
183
+ }
184
+ if (!sameList(current.trustIdentifiers, entry.trustIdentifiers) && !identifierChange) {
185
+ throw new Error(`trust entry ${entry.controlPlaneId}: changing its trust identifier is a rotation step, not a connect or repair; nothing was changed`)
186
+ }
187
+ if (!moved && sameList(current.trustIdentifiers, entry.trustIdentifiers)) return serialize(parsed)
188
+ }
189
+ const others = parsed.filter((p) => p.entry.controlPlaneId !== entry.controlPlaneId)
190
+ const merged = serialize([...others, { raw: JSON.stringify(entry), entry }])
191
+ for (const other of others) if (!merged.includes(other.raw)) throw new Error(`trust entry ${other.entry.controlPlaneId} would not survive the merge`)
192
+ return merged
193
+ }
194
+
195
+ /**
196
+ * The control-plane ids in a TrustEntries value, sorted.
197
+ * @param {string} text
198
+ */
199
+ function controlPlaneIds(text) {
200
+ return parseTrustEntries(text).map((p) => p.entry.controlPlaneId).sort()
201
+ }
202
+
203
+ /**
204
+ * One `sts:AssumeRole` statement per entry, in controlPlaneId order: that control plane's account principal, its caller
205
+ * allowlist for the role and its trust identifiers. The support role also pins the session name.
206
+ * @param {string} text @param {EntryRole} role
207
+ */
208
+ function renderTrustStatements(text, role) {
209
+ const parsed = parseTrustEntries(text)
210
+ if (!parsed.length) throw new Error('the foundation needs at least one trust entry')
211
+ const sorted = [...parsed].sort((a, b) => (a.entry.controlPlaneId < b.entry.controlPlaneId ? -1 : 1))
212
+ return sorted.map(({ entry }) => ({
213
+ Effect: 'Allow',
214
+ Principal: { AWS: `arn:aws:iam::${entry.principalAccountId}:root` },
215
+ Action: 'sts:AssumeRole',
216
+ Condition: {
217
+ StringEquals: { 'sts:ExternalId': [...entry.trustIdentifiers], 'aws:PrincipalArn': [...entry[ENTRY_ROLES[role].callers]] },
218
+ ...(role === 'support' ? { StringLike: { 'sts:RoleSessionName': SUPPORT_SESSION_NAME } } : {}),
219
+ },
220
+ }))
221
+ }
222
+
223
+ /**
224
+ * A rendered trust policy's size as IAM counts it (without whitespace).
225
+ * @param {object[]} statements
226
+ */
227
+ function trustPolicySize(statements) {
228
+ return JSON.stringify({ Version: '2012-10-17', Statement: statements }).length
229
+ }
230
+
231
+ /** The largest TrustEntries value the supported capacity allows: 3 control planes, 2 longest identifiers each. */
232
+ function worstCaseTrustEntries() {
233
+ const entries = []
234
+ for (let i = 0; i < MAX_CONTROL_PLANES; i++) {
235
+ const controlPlaneId = `c${String(i).repeat(MAX_CONTROL_PLANE_ID_LENGTH - 1)}`
236
+ const trustIdentifiers = Array.from({ length: MAX_TRUST_IDENTIFIERS }, (_, n) => String(n).repeat(MAX_TRUST_IDENTIFIER_LENGTH))
237
+ entries.push(controlPlaneEntry({ controlPlaneId, principalAccountId: `${i}`.repeat(12), trustIdentifiers }))
238
+ }
239
+ return JSON.stringify(entries)
240
+ }
241
+
242
+ /**
243
+ * Refuses a TrustEntries value that would not fit: more control planes than supported, a parameter over 4,096 bytes or a
244
+ * rendered trust policy over the quota. The worst case is checked too, so a supported set can always be written.
245
+ * @param {string} text
246
+ * @param {{ maxBytes?: number, maxPolicyChars?: number }} [limits]
247
+ */
248
+ function assertTrustCapacity(text, { maxBytes = TRUST_ENTRIES_MAX_BYTES, maxPolicyChars = TRUST_POLICY_MAX_CHARS } = {}) {
249
+ const check = (value, label) => {
250
+ const parsed = parseTrustEntries(value)
251
+ if (parsed.length > MAX_CONTROL_PLANES) throw new Error(`${label} names ${parsed.length} control planes; a foundation supports at most ${MAX_CONTROL_PLANES} control planes`)
252
+ const bytes = Buffer.byteLength(value, 'utf8')
253
+ if (bytes > maxBytes) throw new Error(`${label} is ${bytes} bytes, which exceeds the ${maxBytes}-byte TrustEntries parameter limit`)
254
+ for (const role of /** @type {EntryRole[]} */ (['deploy', 'support'])) {
255
+ const size = trustPolicySize(renderTrustStatements(value, role))
256
+ if (size > maxPolicyChars) throw new Error(`${label}: the ${role} role trust policy is ${size} characters, which exceeds the ${maxPolicyChars}-character IAM quota`)
257
+ }
258
+ }
259
+ check(worstCaseTrustEntries(), 'the worst-case TrustEntries')
260
+ check(text, 'TrustEntries')
261
+ }
262
+
263
+ /**
264
+ * Single-line JSON with a space after each `:` and `,`, so the text is the same value in JSON and YAML flow syntax.
265
+ * @param {unknown} value
266
+ * @returns {string}
267
+ */
268
+ function flowJson(value) {
269
+ if (Array.isArray(value)) return `[${value.map(flowJson).join(', ')}]`
270
+ if (value && typeof value === 'object') return `{${Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}: ${flowJson(v)}`).join(', ')}}`
271
+ return JSON.stringify(value)
272
+ }
273
+
274
+ /**
275
+ * The [start, end) line range of a top-level resource block in the template.
276
+ * @param {string[]} lines @param {string} logicalId
277
+ */
278
+ function resourceBlock(lines, logicalId) {
279
+ const start = lines.indexOf(` ${logicalId}:`)
280
+ if (start === -1) throw new Error(`the foundation template has no ${logicalId} resource`)
281
+ let end = start + 1
282
+ while (end < lines.length && !/^ {0,2}\S/.test(lines[end])) end++
283
+ return [start, end]
284
+ }
285
+
286
+ /**
287
+ * Replaces an entry role's single-line `Statement: [...]` under its AssumeRolePolicyDocument.
288
+ * @param {string[]} lines @param {EntryRole} role @param {string} text
289
+ */
290
+ function patchTrustStatements(lines, role, text) {
291
+ const { logicalId } = ENTRY_ROLES[role]
292
+ const [start, end] = resourceBlock(lines, logicalId)
293
+ const doc = lines.slice(start, end).findIndex((line) => /^\s+AssumeRolePolicyDocument:\s*$/.test(line))
294
+ const at = doc === -1 ? -1 : lines.slice(start + doc, end).findIndex((line) => /^\s+Statement:/.test(line))
295
+ const index = at === -1 ? -1 : start + doc + at
296
+ const match = index === -1 ? null : /^(\s+)Statement: \[.*\]\s*$/.exec(lines[index])
297
+ if (!match) throw new Error(`${logicalId} does not carry single-line rendered trust statements (a foundation older than the TrustEntries contract)`)
298
+ lines[index] = `${match[1]}Statement: ${flowJson(renderTrustStatements(text, role))}`
299
+ }
300
+
301
+ /**
302
+ * Replaces the controlPlanes literal of the connection-authorizers SSM parameter value.
303
+ * @param {string[]} lines @param {string} text
304
+ */
305
+ function patchControlPlanes(lines, text) {
306
+ const [start, end] = resourceBlock(lines, AUTHORIZERS_PARAMETER)
307
+ const lead = lines.slice(start, end).findIndex((line) => line.trim() === CONTROL_PLANES_LEAD)
308
+ const index = lead === -1 ? -1 : start + lead + 1
309
+ const match = index === -1 ? null : /^(\s+)- '\[.*\]'\s*$/.exec(lines[index])
310
+ if (!match) throw new Error(`${AUTHORIZERS_PARAMETER} does not carry a controlPlanes literal`)
311
+ lines[index] = `${match[1]}- '${JSON.stringify(controlPlaneIds(text))}'`
312
+ }
313
+
314
+ /**
315
+ * The foundation template with its trust rendered from `text`: only the deploy and support roles'
316
+ * `AssumeRolePolicyDocument.Statement` lines and the SSM controlPlanes literal change. Works on the bundled template and
317
+ * on an installed one (GetTemplate Original) alike; refuses when capacity would be exceeded.
318
+ * @param {string} templateText @param {string} text the merged TrustEntries
319
+ * @returns {string}
320
+ */
321
+ function renderFoundationTemplate(templateText, text) {
322
+ assertTrustCapacity(text)
323
+ const lines = templateText.split('\n')
324
+ patchTrustStatements(lines, 'deploy', text)
325
+ patchTrustStatements(lines, 'support', text)
326
+ patchControlPlanes(lines, text)
327
+ return lines.join('\n')
328
+ }
329
+
330
+ /**
331
+ * An authorizer ARN in its stored form: the path-less role ARN. Assumed-role session ARNs map to their role; other
332
+ * principals (users) are kept as given.
333
+ * @param {string} arn
334
+ * @returns {string}
335
+ */
336
+ function canonicalRoleArn(arn) {
337
+ const session = /^arn:aws:sts::([0-9]{12}):assumed-role\/([^/]+)\/.+$/.exec(String(arn))
338
+ if (session) return `arn:aws:iam::${session[1]}:role/${session[2]}`
339
+ const role = /^arn:aws:iam::([0-9]{12}):role\/(?:.*\/)?([^/]+)$/.exec(String(arn))
340
+ if (role) return `arn:aws:iam::${role[1]}:role/${role[2]}`
341
+ if (/^arn:aws:iam::[0-9]{12}:\S+$/.test(String(arn))) return String(arn)
342
+ throw new Error(`${JSON.stringify(arn)} is not an IAM principal ARN`)
343
+ }
344
+
345
+ module.exports = {
346
+ TRUST_ENTRIES_VERSION, MAX_CONTROL_PLANES, MAX_TRUST_IDENTIFIERS, MAX_TRUST_IDENTIFIER_LENGTH, TRUST_ENTRIES_MAX_BYTES, TRUST_POLICY_MAX_CHARS,
347
+ ENTRY_ROLES, AUTHORIZERS_PARAMETER,
348
+ controlPlaneEntry, identityArn, parseTrustEntries, mergeTrustEntry, controlPlaneIds, renderTrustStatements, trustPolicySize,
349
+ worstCaseTrustEntries, assertTrustCapacity, renderFoundationTemplate, canonicalRoleArn,
350
+ }