saaslayer 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -174,6 +174,33 @@ saaslayer first-admin recover --env prod --email new-admin@example.com --reason
174
174
  `GET /access-admins` reports): hand the role over with `saaslayer permissions access-admins offer` instead.
175
175
  - Both start an operation and wait for it (`--no-wait` returns); the deployment's activity records who asked and why.
176
176
 
177
+ ### External ID token and `saaslayer permissions trust-policies`
178
+
179
+ On a deployment that trusts your own login provider (Cognito, Auth0, Okta, …), an administrator signs in with an ID
180
+ token from that provider. `--id-token-file FILE` (or `$SAASLAYER_ID_TOKEN`) works with the `saaslayer permissions`
181
+ commands:
182
+
183
+ ```bash
184
+ chmod 600 id.jwt
185
+ saaslayer permissions access-admins activate --id-token-file id.jwt --deployment dep_…
186
+ saaslayer permissions trust-policies list --id-token-file id.jwt --deployment dep_…
187
+ saaslayer permissions trust-policies add https://acme.okta.com --audience 0oa1admin --allow-any-subject \
188
+ --id-token-file id.jwt --deployment dep_…
189
+ ```
190
+
191
+ - Pass the **ID token**, not an access token. Cognito access tokens carry no `aud`, and the deployment only accepts a
192
+ token whose `aud` is one of the provider's allowed audiences. Use a dedicated app client for administrators so its
193
+ client id can be the only admin audience.
194
+ - The token only goes to a pinned host: `--deployment` (the deployment's permissions API, read through the control
195
+ plane with your `saaslayer login`) or an https `--api-base` whose host you type to confirm (`--yes` confirms). An
196
+ expired token is refused before anything is sent. The token is never printed.
197
+ - `trust-policies add` reads `<issuer>/.well-known/openid-configuration` and refuses unless it names exactly that
198
+ issuer. `delete` needs `--reason` and the issuer typed to confirm. The deployment's own pool is read-only
199
+ (`409 FIRST_PARTY_POLICY`), and a change that would leave no usable access admin a way to sign in is refused
200
+ (`409 LAST_ADMIN_PROVIDER`).
201
+
202
+ Full guide: [docs/permissions-only.md](../../docs/permissions-only.md).
203
+
177
204
  ## License
178
205
 
179
206
  Proprietary. All rights reserved. See [LICENSE](./LICENSE).
package/bin/saaslayer.js CHANGED
@@ -53,9 +53,13 @@ Usage:
53
53
  own trust, as your saaslayer login (no AWS credentials are sent), so the console and deploys see the new
54
54
  version; if that fails the upgrade still stands and the console's "check again" re-reads it.
55
55
 
56
- saaslayer signup [--config-url URL] [--email E --password P]
57
- Create a SaaSLayer account (allowlist-gated) and log in.
56
+ saaslayer signup [--config-url URL] [--email E --password P] [--code C | --resend]
57
+ Create a SaaSLayer account (allowlist-gated), confirm the code emailed to you (prompted, or --code), and log in.
58
+ Without a terminal it stops once the code is sent; finish with --code. --resend emails a new code.
58
59
  --config-url (or $SAASLAYER_CONFIG_URL) is the control-plane API; default https://api.saaslayer.com.
60
+ saaslayer account verify-email [--code C]
61
+ Prove the logged-in account owns its email (a code is emailed; type it, or pass --code). Org owners can add
62
+ only accounts whose email is verified.
59
63
  saaslayer login [--email E --password P] [--config-url URL | --user-pool-id ID --client-id ID --region R]
60
64
  Log in to your SaaSLayer account (Cognito SRP) and cache tokens in ~/.saaslayer.
61
65
  Email/password fall back to $SAASLAYER_EMAIL/$SAASLAYER_PASSWORD, else prompt.
@@ -65,7 +69,8 @@ Usage:
65
69
  Log in to a deployment's user-service as an access admin. The pool, client and API bases are
66
70
  discovered from the deployment's public outputs (an env name resolves the active project's deployment).
67
71
  Kept separate from your control-plane login, which stays logged in.
68
- saaslayer whoami Show the current logged-in account, its control plane, and the active org/project.
72
+ saaslayer whoami Show the current logged-in account, its account id (share it with an org owner to be added
73
+ to their org), its control plane, and the active org/project.
69
74
  saaslayer context [--json] [--profile AWS_PROFILE] Show the control-plane account, the deployment login, the AWS
70
75
  profile, org and project (and where each came from) and every cached identity.
71
76
  Tokens are never printed.
@@ -139,6 +144,25 @@ Usage:
139
144
  once; it counts once they accept with their own deployment login. --mode transfer (default) then removes you,
140
145
  add keeps you. An interrupted accept leaves both admins; accept again to finish. cancel (pending offers, by you)
141
146
  revokes the grant. activate records your own activation. See services/permissions-service/user-docs/access-admins.md.
147
+ saaslayer permissions trust-policies list | get <policyId> (--deployment ID | --api-base URL) [auth]
148
+ saaslayer permissions trust-policies add <issuerUrl> --audience A [--audience B] (--subject S … | --allow-any-subject)
149
+ [--principal-claim sub] [--jwks-uri URL] [--description D] (--deployment ID | --api-base URL) [auth]
150
+ saaslayer permissions trust-policies update <policyId> [--audience A …] [--subject S … | --allow-any-subject] [--jwks-uri URL] [--description D] …
151
+ saaslayer permissions trust-policies disable | enable <policyId> (--deployment ID | --api-base URL) [auth]
152
+ saaslayer permissions trust-policies delete <policyId> --reason TEXT [--yes] (--deployment ID | --api-base URL) [auth]
153
+ The external login providers (OIDC issuers: your Cognito pool, Auth0, Okta, …) whose ID tokens the deployment accepts.
154
+ Needs an access admin (or a trust-manager holder). <issuerUrl> is the EXACT iss of the provider's ID tokens: add
155
+ refuses unless <issuerUrl>/.well-known/openid-configuration names it. Providers added here are external (people get
156
+ ext_ principal ids) and never impersonate; the deployment's own pool is read-only (409 FIRST_PARTY_POLICY). A change
157
+ that would leave no usable access admin a way to sign in is refused (409 LAST_ADMIN_PROVIDER). delete asks you to
158
+ type the issuer (--yes confirms). See docs/permissions-only.md.
159
+ External ID token (saaslayer permissions commands):
160
+ --id-token-file FILE (or $SAASLAYER_ID_TOKEN) sends the raw OIDC ID token from your own login provider as the
161
+ credential — e.g. \`saaslayer permissions access-admins activate --id-token-file id.jwt --deployment dep_…\`. It goes
162
+ only to a pinned host: --deployment <dep_id|env> (its permissions API, read through the control plane with your
163
+ \`saaslayer login\`; commands that need --api-base must name that same API) or an https --api-base whose host you
164
+ type to confirm (--yes confirms). Expired tokens and access tokens are refused locally; never combined with --iam,
165
+ --token, $SAASLAYER_TOKEN or a deployment login; the token is never printed. Keep the file chmod 600.
142
166
 
143
167
  saaslayer users export --provider cognito --user-pool-id POOL --region R [--profile P]
144
168
  [--account-attribute ATTR] [--account-name-attribute ATTR] [--role-map map.js] --out manifest.json
@@ -190,12 +214,33 @@ Usage:
190
214
  For a user who lost every MFA factor: removes their passkeys and authenticator-app MFA and signs them out
191
215
  everywhere, so they can enroll a new factor. Access admins only (never --iam); the reason
192
216
  goes to the audit line. Resetting your own MFA needs a fresh MFA sign-in.
217
+ saaslayer users admin bootstrap|keys|grants --deployment <id> --service <ref> --account-id <id> --region <r>
218
+ [--profile <p> --manifest <file>] [--wait]
219
+ Opt-in local management of one user-service instance (off by default): owners, machine keys and human grants
220
+ with fixed purposes, usable without the control plane or permissions-service. Standalone (--manifest, your
221
+ target-account IAM; the manifest is checked against the stack before any write) or managed (an owner of the
222
+ deployment's owning org, through the control plane).
223
+ bootstrap --owner-suid <suid> --owner-email <email> [repeat] --purpose <p> [repeat] [--reason <text>]
224
+ keys --caller <id> --purpose <p> --phase introduce --output <private-file>
225
+ keys --caller <id> --phase activate|retire|revoke --key-id <id> [--reason <text>] | keys --phase status
226
+ grants --principal <suid> [repeat] --purpose <p> --phase grant|revoke|status [--reason <text>]
227
+ Purposes: account-read, account-provisioning, account-import, account-administration, account-deletion,
228
+ account-sensitive, account-recovery (humans only), reconciliation, config, email-authoring. A raw key is written
229
+ only to --output (0600); revoke needs --reason; a revoked grant or root comes back only with --reason.
193
230
 
194
231
  Deploy & lifecycle (requires login + a connected AWS account):
195
232
  saaslayer aws connect --aws-account <id> [--region R] [--org ID] [--org-wide]
196
233
  Connect your AWS account to an org. Binds it to your active project by
197
234
  default; --org-wide lets any project in the org deploy into it.
198
235
  saaslayer project use <id> Set the active project for deploy/status (a project id tnt_… or a customer id).
236
+ saaslayer org members list [--org ID]
237
+ saaslayer org members add --user <accountId> [--role deployer] [--org ID] [--yes]
238
+ saaslayer org members remove --user <accountId> [--org ID]
239
+ saaslayer org members set-role --user <accountId> --role deployer|member [--org ID]
240
+ Org owners only: manage the org's members by account id (the teammate prints it with \`saaslayer whoami\`). add
241
+ shows the account's email and asks for it to be typed back unless --yes; an account whose email is not verified
242
+ is refused (EMAIL_NOT_PROVEN). A deployer may update deployments and cancel its own runs; owner powers stay with
243
+ owners. remove revokes the deployer role, then the membership. --org defaults to the active org.
199
244
  saaslayer project destroy [<id>] [--yes]
200
245
  Delete a project (the active one by default) and release its public name for reuse. Refused while any of its
201
246
  deployments is live: destroy each with \`saaslayer destroy\` first. Asks for the id to be typed unless --yes.
@@ -279,6 +324,11 @@ Deploy & lifecycle (requires login + a connected AWS account):
279
324
  saaslayer activity --env E [--region R | --deployment ID] [--limit N] [--json]
280
325
  A deployment's activity, newest first: every change — yours and any SaaSLayer operator's — with who made it
281
326
  (customer:<id> | operator:<id>), the action, what it touched, the reason and its operation id.
327
+ saaslayer credentials status --deployment <id> --service <ref> [--json]
328
+ saaslayer credentials revoke --deployment <id> --service <ref> --kind email-authoring|config --key-id <id> --reason <text> [--json]
329
+ Org owners: a user-service instance's console integration credentials (key ids, state, age; never a value), and an
330
+ emergency revoke of one key (no delay). The revoke answers its pending operation; the key stops working once every
331
+ verifier holds the replacement.
282
332
 
283
333
  Data migrations you run yourself (a deployment with migrationRunner self):
284
334
  saaslayer migrate status --deployment <id> [--service <ref>]
@@ -295,6 +345,11 @@ Data migrations you run yourself (a deployment with migrationRunner self):
295
345
  Standalone (no control plane, no report): --stack <stackName> --region <r>, with --repo the service dir.
296
346
  Exit codes: 0 ok / up-to-date, 1 failed, 2 awaiting approval, 3 applied but not reported.
297
347
 
348
+ Platform operators:
349
+ saaslayer admin allowlist list | add <email> | remove <email>
350
+ The control plane's signup allowlist (the login pool's PreSignUp gate for console and CLI signup). Operators
351
+ only; the control plane refuses anyone else.
352
+
298
353
  Global:
299
354
  --help Show this help.`
300
355
 
@@ -379,17 +434,25 @@ async function main() {
379
434
  if (run) { console.log(JSON.stringify(await run(rest, flags), null, 2)); return }
380
435
  console.error('usage: saaslayer permissions access-admins <list|offer|status|cancel|accept|activate> [suid|transferId] --api-base URL'); process.exit(1)
381
436
  }
437
+ if (cmd === 'permissions' && sub === 'trust-policies') {
438
+ const tp = require('../src/commands/trust-policies')
439
+ const rest = positional.slice(3)
440
+ const run = { list: tp.trustPoliciesList, get: tp.trustPoliciesGet, add: tp.trustPoliciesAdd, update: tp.trustPoliciesUpdate, disable: tp.trustPoliciesDisable, enable: tp.trustPoliciesEnable, delete: tp.trustPoliciesDelete }[positional[2]]
441
+ if (run) { console.log(JSON.stringify(await run(rest, flags), null, 2)); return }
442
+ console.error('usage: saaslayer permissions trust-policies <list|get|add|update|disable|enable|delete> [policyId|issuerUrl] (--deployment ID | --api-base URL) [auth]'); process.exit(1)
443
+ }
382
444
  if (cmd === 'users') {
383
445
  const users = require('../src/commands/users')
384
446
  if (sub === 'export') { await users.usersExport(flags); return }
385
447
  if (sub === 'import') { await users.usersImport(flags); return }
448
+ if (sub === 'admin') { await require('../src/commands/users-management').usersManagement(positional[2], flags); return }
386
449
  if (users.ADMIN_COMMANDS.includes(sub)) { await users.usersAdmin(sub, positional.slice(2), flags); return }
387
450
  console.error(users.USAGE); process.exit(1)
388
451
  }
389
452
  if (cmd === 'signup') {
390
453
  const { signup } = require('../src/commands/login')
391
- const who = await signup(flags)
392
- console.log(`account created — logged in as ${who.email}`)
454
+ const out = await signup(flags)
455
+ console.log(out.status === 'logged-in' ? `account created — logged in as ${out.email}` : out.next)
393
456
  return
394
457
  }
395
458
  if (cmd === 'login') {
@@ -430,6 +493,7 @@ async function main() {
430
493
  const who = whoami()
431
494
  if (!who) { console.log('not logged in'); return }
432
495
  console.log(`${who.email} (control plane: ${who.env})`)
496
+ if (who.accountId) console.log(`account id: ${who.accountId} (share this id with your org owner to be added to their org)`)
433
497
  const ctx = require('../src/context-store').load()
434
498
  console.log(`org: ${ctx.org || '—'} project: ${ctx.project ? `${ctx.project} (${require('../src/scope').projectIdKind(ctx.project)})` : '—'} (see: saaslayer context)`)
435
499
  return
@@ -452,6 +516,11 @@ async function main() {
452
516
  console.log('\n* = active. Switch with: saaslayer account use <email>')
453
517
  return
454
518
  }
519
+ if (cmd === 'account' && sub === 'verify-email') {
520
+ const out = await require('../src/commands/account-email').verifyEmail(flags)
521
+ console.log(out.status === 'verified' ? `email verified: ${out.email}` : out.next)
522
+ return
523
+ }
455
524
  if (cmd === 'account' && sub === 'use') {
456
525
  const { accountUse } = require('../src/commands/accounts')
457
526
  const who = accountUse(positional[2])
@@ -463,7 +532,16 @@ async function main() {
463
532
  if (sub === 'create') { const o = await orgs.orgCreate(flags, positional[2]); console.log(`created org ${o.name || ''} (${o.id}) — now active`); return }
464
533
  if (sub === 'list') { const list = await orgs.orgList(flags); if (!list.length) console.log('no orgs'); else list.forEach((o) => console.log(`${o.id}${o.name ? ' ' + o.name : ''}`)); return }
465
534
  if (sub === 'use') { const id = orgs.orgUse(flags, positional[2]); console.log(`active org: ${id}`); return }
466
- console.error('usage: saaslayer org <create|list|use> …'); process.exit(1)
535
+ if (sub === 'members') {
536
+ const members = require('../src/commands/org-members')
537
+ const action = positional[2]
538
+ if (action === 'list') { await members.membersList(flags); return }
539
+ if (action === 'add') { await members.membersAdd(flags, {}, positional[3]); return }
540
+ if (action === 'remove') { await members.membersRemove(flags, positional[3]); return }
541
+ if (action === 'set-role') { await members.membersSetRole(flags, positional[3]); return }
542
+ console.error('usage: saaslayer org members <list|add|remove|set-role> [--user <accountId>] [--role deployer|member] [--org ID]'); process.exit(1)
543
+ }
544
+ console.error('usage: saaslayer org <create|list|use|members> …'); process.exit(1)
467
545
  }
468
546
  if (cmd === 'project') {
469
547
  const orgs = require('../src/commands/orgs')
@@ -489,6 +567,12 @@ async function main() {
489
567
  if (sub === 'upgrade') { await foundation.foundationUpgrade(flags); return }
490
568
  console.error('usage: saaslayer foundation <status|upgrade> [--region R] [--profile P] (see saaslayer --help)'); process.exit(1)
491
569
  }
570
+ if (cmd === 'admin' && sub === 'allowlist') {
571
+ const allowlist = require('../src/commands/admin-allowlist')
572
+ const run = { list: allowlist.allowlistList, add: allowlist.allowlistAdd, remove: allowlist.allowlistRemove }[positional[2]]
573
+ if (run) { await run(flags, positional[3]); return }
574
+ console.error('usage: saaslayer admin allowlist <list|add <email>|remove <email>>'); process.exit(1)
575
+ }
492
576
  if (cmd === 'stacks') { const { stacks } = require('../src/commands/stacks'); await stacks(flags); return }
493
577
  if (cmd === 'deploy') { const { deploy } = require('../src/commands/deploy'); await deploy(flags); return }
494
578
  if (cmd === 'status') { const { status } = require('../src/commands/lifecycle'); await status(flags); return }
@@ -508,6 +592,8 @@ async function main() {
508
592
  if (cmd === 'settings') { const { settingsCommand } = require('../src/commands/settings'); await settingsCommand(sub, flags); return }
509
593
  if (cmd === 'first-admin') { const { firstAdminCommand } = require('../src/commands/first-admin'); await firstAdminCommand(sub, flags); return }
510
594
  if (cmd === 'activity') { const { activityCommand } = require('../src/commands/activity'); await activityCommand(flags); return }
595
+ if (cmd === 'credentials' && sub === 'status') { await require('../src/commands/integration-credentials').credentialsStatus(flags); return }
596
+ if (cmd === 'credentials' && sub === 'revoke') { await require('../src/commands/integration-credentials').credentialsRevoke(flags); return }
511
597
  if (cmd === 'operations' || cmd === 'operation') { const { operationsCommand } = require('../src/commands/operations'); await operationsCommand(sub, positional[2], flags); return }
512
598
  if (cmd === 'service') {
513
599
  const lc = require('../src/commands/lifecycle')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "saaslayer",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "SaaSLayer CLI — onboard an account (init) and register a service's permissions manifest.",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -41,7 +41,7 @@
41
41
  "access": "public"
42
42
  },
43
43
  "scripts": {
44
- "test": "node scripts/sync-template.js --check && node scripts/sync-vendor.js --check && node bin/saaslayer.js --help >/dev/null && node test/credentials.test.js && node test/multi-account.test.js && node test/aws.test.js && node test/api-client-refresh.test.js && node test/update.test.js && node test/migrations-approve.test.js && node test/service-remove.test.js && node test/settings.test.js && node test/env-compare.test.js && node test/release-manifest.test.js && node test/operations.test.js && node test/projects.test.js && node test/activity.test.js && node test/deploy.test.js && node test/module-catalog.test.js && node test/stacks.test.js && node test/catalog.test.js && node test/catalog-registry.test.js && node test/permissions-inspect.test.js && node test/permissions-commands.test.js && node test/iam.test.js && node test/machine-trust.test.js && node test/access-admins.test.js && node test/first-admin.test.js && node test/service-principals.test.js && node test/package-files.test.js && node test/users-export.test.js && node test/users-import.test.js && node test/users.test.js && node test/migrate.test.js && node test/foundation-template.test.js && node test/foundation.test.js && node test/scope.test.js && node test/discovery.test.js && node test/credential-profiles.test.js && node test/login-challenges.test.js && node test/login-prompt.test.js && node test/control-plane-url.test.js && echo ok",
44
+ "test": "node scripts/sync-template.js --check && node scripts/sync-vendor.js --check && node bin/saaslayer.js --help >/dev/null && node test/credentials.test.js && node test/multi-account.test.js && node test/aws.test.js && node test/api-client-refresh.test.js && node test/update.test.js && node test/migrations-approve.test.js && node test/service-remove.test.js && node test/settings.test.js && node test/env-compare.test.js && node test/release-manifest.test.js && node test/operations.test.js && node test/projects.test.js && node test/activity.test.js && node test/integration-credentials.test.js && node test/users-management.test.js && node test/deploy.test.js && node test/module-catalog.test.js && node test/stacks.test.js && node test/catalog.test.js && node test/catalog-registry.test.js && node test/permissions-inspect.test.js && node test/permissions-commands.test.js && node test/iam.test.js && node test/machine-trust.test.js && node test/access-admins.test.js && node test/first-admin.test.js && node test/service-principals.test.js && node test/package-files.test.js && node test/users-export.test.js && node test/users-import.test.js && node test/users.test.js && node test/migrate.test.js && node test/foundation-template.test.js && node test/foundation.test.js && node test/scope.test.js && node test/discovery.test.js && node test/credential-profiles.test.js && node test/login-challenges.test.js && node test/login-prompt.test.js && node test/control-plane-url.test.js && node test/signup.test.js && node test/org-members.test.js && echo ok && node test/id-token-auth.test.js && node test/trust-policies.test.js",
45
45
  "sync-template": "node scripts/sync-template.js",
46
46
  "sync-template:check": "node scripts/sync-template.js --check",
47
47
  "prepublishOnly": "node scripts/sync-template.js",
package/src/api-client.js CHANGED
@@ -69,6 +69,24 @@ async function freshBearer(flags = {}) {
69
69
  return (await refreshTokens(current, flags)).idToken
70
70
  }
71
71
 
72
+ /**
73
+ * The current control-plane login with a usable access token (refreshed first when expired): the token Cognito's
74
+ * own-account calls (email verification) take.
75
+ * @param {object} [flags]
76
+ * @returns {Promise<{ accessToken: string, region: string, email: string }>}
77
+ */
78
+ async function freshAccessLogin(flags = {}) {
79
+ let current = creds.getCurrent()
80
+ if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
81
+ if (!isFresh(current) || !current.accessToken) {
82
+ if (!current.refreshToken) throw new Error('session expired — run `saaslayer login`')
83
+ current = await refreshTokens(current, flags)
84
+ }
85
+ if (!current.accessToken) throw new Error('this login has no access token — run `saaslayer login`')
86
+ const region = current.region || (await resolvePoolConfig(flags)).region
87
+ return { accessToken: current.accessToken, region, email: current.email }
88
+ }
89
+
72
90
  /**
73
91
  * @param {string} method
74
92
  * @param {string} path
@@ -88,4 +106,22 @@ async function apiCall(method, path, body, flags, opts = {}) {
88
106
  return doc
89
107
  }
90
108
 
91
- module.exports = { apiBase, bearer, freshBearer, apiCall, isFresh, refreshCognitoTokens }
109
+ /**
110
+ * apiCall for a JSON:API route: a refusal is rethrown as `<code>: <title>` (status and body kept), so the user reads the
111
+ * server's reason instead of the raw document.
112
+ * @param {string} method
113
+ * @param {string} path
114
+ * @param {unknown} [body]
115
+ * @param {object} [flags]
116
+ */
117
+ async function jsonApiCall(method, path, body, flags) {
118
+ try {
119
+ return await apiCall(method, path, body, flags)
120
+ } catch (err) {
121
+ const first = err && err.body && Array.isArray(err.body.errors) ? err.body.errors[0] : null
122
+ if (!first) throw err
123
+ throw Object.assign(new Error(`${first.code || err.status}: ${first.title || first.detail || 'request refused'}`), { status: err.status, body: err.body })
124
+ }
125
+ }
126
+
127
+ module.exports = { apiBase, bearer, freshBearer, freshAccessLogin, apiCall, jsonApiCall, isFresh, refreshCognitoTokens }
@@ -0,0 +1,80 @@
1
+ // The public (unsigned) Cognito user-pool calls the CLI makes for an account: sign up, confirm the emailed code, resend
2
+ // it, and verify the email of a signed-in account. Same calls the console makes; no AWS credentials involved.
3
+ 'use strict'
4
+
5
+ /**
6
+ * @typedef {{ region: string, clientId: string }} PoolClient
7
+ * @typedef {Error & { code?: string, status?: number }} CognitoError
8
+ */
9
+
10
+ /**
11
+ * One Cognito Identity Provider JSON call. A refusal throws with the exception name as `code` and Cognito's message.
12
+ * @param {string} region
13
+ * @param {string} operation e.g. SignUp
14
+ * @param {Record<string, unknown>} body
15
+ * @returns {Promise<Record<string, any>>}
16
+ */
17
+ async function cognitoCall(region, operation, body) {
18
+ const res = await fetch(`https://cognito-idp.${region}.amazonaws.com/`, {
19
+ method: 'POST',
20
+ headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}` },
21
+ body: JSON.stringify(body),
22
+ })
23
+ const doc = await res.json().catch(() => ({}))
24
+ if (!res.ok) {
25
+ const code = String(doc.__type || '').split('#').pop() || `HTTP_${res.status}`
26
+ /** @type {CognitoError} */
27
+ const err = new Error(doc.message || doc.Message || `${operation} failed (${res.status})`)
28
+ err.code = code
29
+ err.status = res.status
30
+ throw err
31
+ }
32
+ return doc
33
+ }
34
+
35
+ /**
36
+ * Create an unconfirmed account; Cognito emails a confirmation code (the pool's PreSignUp allowlist runs first).
37
+ * @param {PoolClient} pool
38
+ * @param {{ email: string, password: string }} input
39
+ */
40
+ function signUp(pool, { email, password }) {
41
+ return cognitoCall(pool.region, 'SignUp', { ClientId: pool.clientId, Username: email, Password: password, UserAttributes: [{ Name: 'email', Value: email }] })
42
+ }
43
+
44
+ /**
45
+ * Confirm a signup with the emailed code: the account is CONFIRMED and its email verified.
46
+ * @param {PoolClient} pool
47
+ * @param {{ email: string, code: string }} input
48
+ */
49
+ function confirmSignUp(pool, { email, code }) {
50
+ return cognitoCall(pool.region, 'ConfirmSignUp', { ClientId: pool.clientId, Username: email, ConfirmationCode: code })
51
+ }
52
+
53
+ /**
54
+ * Email a new signup confirmation code.
55
+ * @param {PoolClient} pool
56
+ * @param {{ email: string }} input
57
+ */
58
+ function resendConfirmationCode(pool, { email }) {
59
+ return cognitoCall(pool.region, 'ResendConfirmationCode', { ClientId: pool.clientId, Username: email })
60
+ }
61
+
62
+ /**
63
+ * Email a verification code to the signed-in account's email.
64
+ * @param {string} region
65
+ * @param {{ accessToken: string }} input
66
+ */
67
+ function getEmailVerificationCode(region, { accessToken }) {
68
+ return cognitoCall(region, 'GetUserAttributeVerificationCode', { AccessToken: accessToken, AttributeName: 'email' })
69
+ }
70
+
71
+ /**
72
+ * Verify the signed-in account's email with the emailed code (sets email_verified=true).
73
+ * @param {string} region
74
+ * @param {{ accessToken: string, code: string }} input
75
+ */
76
+ function verifyEmailCode(region, { accessToken, code }) {
77
+ return cognitoCall(region, 'VerifyUserAttribute', { AccessToken: accessToken, AttributeName: 'email', Code: code })
78
+ }
79
+
80
+ module.exports = { signUp, confirmSignUp, resendConfirmationCode, getEmailVerificationCode, verifyEmailCode }
@@ -0,0 +1,43 @@
1
+ // `saaslayer account verify-email` — prove the logged-in control-plane account owns its email: Cognito emails a code,
2
+ // the typed (or --code) code verifies it. Org owners can add only accounts whose email is proven.
3
+ 'use strict'
4
+
5
+ /**
6
+ * @typedef {{ isTTY: boolean, prompt: (question: string, opts?: { hidden?: boolean }) => Promise<string> }} PromptIo
7
+ * @typedef {{ status: 'code-sent', email: string, next: string } | { status: 'verified', email: string }} VerifyOutcome
8
+ */
9
+
10
+ /** @type {PromptIo} */
11
+ const terminalIo = {
12
+ get isTTY() { return Boolean(process.stdin.isTTY) },
13
+ prompt: (question, opts) => require('./login').prompt(question, opts),
14
+ }
15
+
16
+ /**
17
+ * Send a verification code to the account's email and verify it. `--code` verifies a code already sent (no new code);
18
+ * without a terminal and no --code it only sends one and names the command that finishes it.
19
+ * @param {Record<string, any>} flags --code, --config-url
20
+ * @param {{ io?: PromptIo }} [deps]
21
+ * @returns {Promise<VerifyOutcome>}
22
+ */
23
+ async function verifyEmail(flags = {}, deps = {}) {
24
+ const io = deps.io || terminalIo
25
+ const cognito = require('../cognito-user-api')
26
+ const { freshAccessLogin } = require('../api-client')
27
+ const { accessToken, region, email } = await freshAccessLogin(flags)
28
+ let code = flags.code !== undefined ? String(flags.code).trim() : ''
29
+ if (!code) {
30
+ const sent = await cognito.getEmailVerificationCode(region, { accessToken })
31
+ const destination = (sent.CodeDeliveryDetails && sent.CodeDeliveryDetails.Destination) || email
32
+ if (!io.isTTY) return { status: 'code-sent', email, next: `check ${destination} for the code, then run: saaslayer account verify-email --code <code>` }
33
+ code = String(await io.prompt(`Code emailed to ${destination}: `)).trim()
34
+ }
35
+ try {
36
+ await cognito.verifyEmailCode(region, { accessToken, code })
37
+ } catch (err) {
38
+ throw new Error(`email not verified: ${err.message} Run \`saaslayer account verify-email\` again for a new code`)
39
+ }
40
+ return { status: 'verified', email }
41
+ }
42
+
43
+ module.exports = { verifyEmail }
@@ -0,0 +1,45 @@
1
+ // `saaslayer admin allowlist list|add|remove <email>` — platform operators manage the control plane's signup allowlist
2
+ // (the login pool's PreSignUp gate). The server refuses anyone who is not a platform operator.
3
+ 'use strict'
4
+ const { jsonApiCall } = require('../api-client')
5
+
6
+ /**
7
+ * @typedef {{ version: number, enabled: boolean, emails: string[] }} Allowlist
8
+ */
9
+
10
+ /** @param {any} doc @returns {Allowlist} */
11
+ function allowlistOf(doc) {
12
+ return doc.data.attributes
13
+ }
14
+
15
+ /** @param {Allowlist} list */
16
+ function print(list) {
17
+ console.log(`signup allowlist (version ${list.version}, ${list.enabled ? 'enforced' : 'not enforced: signup is open'})`)
18
+ if (!list.emails.length) console.log(' (no emails)')
19
+ for (const email of list.emails) console.log(` ${email}`)
20
+ }
21
+
22
+ /** @param {Record<string, any>} flags @returns {Promise<Allowlist>} */
23
+ async function allowlistList(flags = {}) {
24
+ const list = allowlistOf(await jsonApiCall('GET', '/api/signup-allowlist', undefined, flags))
25
+ print(list)
26
+ return list
27
+ }
28
+
29
+ /** @param {Record<string, any>} flags @param {string} [email] @returns {Promise<Allowlist>} */
30
+ async function allowlistAdd(flags = {}, email) {
31
+ if (!email) throw new Error('usage: saaslayer admin allowlist add <email>')
32
+ const list = allowlistOf(await jsonApiCall('POST', '/api/signup-allowlist/emails', { email: String(email).trim().toLowerCase() }, flags))
33
+ print(list)
34
+ return list
35
+ }
36
+
37
+ /** @param {Record<string, any>} flags @param {string} [email] @returns {Promise<Allowlist>} */
38
+ async function allowlistRemove(flags = {}, email) {
39
+ if (!email) throw new Error('usage: saaslayer admin allowlist remove <email>')
40
+ const list = allowlistOf(await jsonApiCall('DELETE', `/api/signup-allowlist/emails/${encodeURIComponent(String(email).trim().toLowerCase())}`, undefined, flags))
41
+ print(list)
42
+ return list
43
+ }
44
+
45
+ module.exports = { allowlistList, allowlistAdd, allowlistRemove }
@@ -80,9 +80,49 @@ function artifactsBucketName(accountId, region) {
80
80
  return `sl-artifacts-${region}-${opaqueAccountToken(accountId, 'artifacts').slice(0, 12)}`
81
81
  }
82
82
 
83
+ // The account's email sender domain, as the region template's EmailSenderDomain AllowedPattern takes it (or '' = none).
84
+ const EMAIL_SENDER_DOMAIN_PATTERN = /^(([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63})?$/
85
+
86
+ /**
87
+ * The --email-sender-domain flag, lowercased and checked before anything touches AWS; undefined when not passed.
88
+ * @param {Record<string, unknown>} flags
89
+ * @returns {string|undefined}
90
+ */
91
+ function emailSenderDomainFlag(flags) {
92
+ const raw = flags['email-sender-domain']
93
+ if (raw === undefined) return undefined
94
+ const domain = String(raw === true ? '' : raw).trim().toLowerCase()
95
+ if (!EMAIL_SENDER_DOMAIN_PATTERN.test(domain)) throw new Error(`--email-sender-domain expects a domain like acme.com ('' removes it), got '${raw}'`)
96
+ return domain
97
+ }
98
+
99
+ /**
100
+ * The region stack's email sender outputs: the SES identity ARN and the DKIM CNAME records for the domain's DNS.
101
+ * @param {Array<{ OutputKey: string, OutputValue: string }>} outputs
102
+ * @returns {{ identityArn: string, records: string[] }|null}
103
+ */
104
+ function emailSenderOutputs(outputs) {
105
+ const value = (key) => ((outputs || []).find((o) => o.OutputKey === key) || {}).OutputValue
106
+ const records = value('EmailSenderDkimRecords')
107
+ if (!records) return null
108
+ return { identityArn: value('EmailSenderIdentityArn') || '', records: records.split('\n').filter(Boolean) }
109
+ }
110
+
111
+ /**
112
+ * Prints what the customer's DNS admin adds, and the setting that sends through the domain once verified.
113
+ * @param {(...a: unknown[]) => void} log @param {string} domain @param {{ identityArn: string, records: string[] }} sender
114
+ */
115
+ function logEmailSenderRecords(log, domain, sender) {
116
+ log(` email sender domain ${domain}: add these DKIM records to its DNS (CNAME, TTL 300 or the default):`)
117
+ for (const record of sender.records) log(` ${record}`)
118
+ log(' once verified (saaslayer foundation status), send through it with:')
119
+ log(` saaslayer settings set CognitoEmailSenderArn=${sender.identityArn} CognitoEmailFromAddress='<Name> <no-reply@${domain}>'`)
120
+ }
121
+
83
122
  // Build the `aws cloudformation deploy` argv for the per-region foundation stack. Pure — unit-testable.
84
- // No IAM in this stack, so no CAPABILITY_NAMED_IAM; a no-op re-deploy must be clean, not a failure.
85
- function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templateFile = FOUNDATION_REGION_TEMPLATE }) {
123
+ // No IAM in this stack, so no CAPABILITY_NAMED_IAM; a no-op re-deploy must be clean, not a failure. Without
124
+ // emailSenderDomain no override is passed, so a re-run keeps the sender domain the stack already has.
125
+ function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templateFile = FOUNDATION_REGION_TEMPLATE, emailSenderDomain }) {
86
126
  return [
87
127
  'cloudformation', 'deploy',
88
128
  '--template-file', templateFile,
@@ -91,13 +131,15 @@ function foundationRegionDeployArgs({ region, artifactsBucketName: bucket, templ
91
131
  '--no-fail-on-empty-changeset',
92
132
  '--parameter-overrides',
93
133
  `ArtifactsBucketName=${bucket}`,
134
+ ...(emailSenderDomain !== undefined ? [`EmailSenderDomain=${emailSenderDomain}`] : []),
94
135
  ]
95
136
  }
96
137
 
97
- // Deploy the per-region foundation stack (shared artifact bucket) with the caller's creds (or injected `env`).
98
- function deployFoundationRegion({ accountId, region, env }) {
138
+ // Deploy the per-region foundation stack (shared artifact bucket, optional email sender domain) with the caller's
139
+ // creds (or injected `env`).
140
+ function deployFoundationRegion({ accountId, region, env, emailSenderDomain }) {
99
141
  const bucket = artifactsBucketName(accountId, region)
100
- execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket }),
142
+ execFileSync('aws', foundationRegionDeployArgs({ region, artifactsBucketName: bucket, emailSenderDomain }),
101
143
  { stdio: 'inherit', env: env ? { ...process.env, ...env } : process.env })
102
144
  return bucket
103
145
  }
@@ -107,6 +149,7 @@ async function awsConnect(flags) {
107
149
  const region = flags.region || 'us-east-1'
108
150
  const orgId = flags.org || context.get('org')
109
151
  if (!accountId) throw new Error('aws connect requires --aws-account <12-digit id>')
152
+ const emailSenderDomain = emailSenderDomainFlag(flags)
110
153
  if (!orgId) throw new Error('no org selected — run `saaslayer org use <id>` or pass --org')
111
154
  // D5: bind the account to the active project by default; --org-wide opens it to all org projects.
112
155
  const orgWide = flags['org-wide'] === true || flags['org-wide'] === 'true'
@@ -118,8 +161,13 @@ async function awsConnect(flags) {
118
161
  console.log(` registered (trust secret minted); deploying the account-global foundation stack into ${accountId} with your AWS creds…`)
119
162
  deployFoundation({ controlPlaneAccount: conn.controlPlaneAccountId, externalId: conn.externalId, region, stackNamePrefix: conn.stackNamePrefix, orgId })
120
163
  console.log(` global foundation deployed; deploying the per-region foundation (shared artifact bucket) into ${region}…`)
121
- const bucket = deployFoundationRegion({ accountId, region })
164
+ const bucket = deployFoundationRegion({ accountId, region, emailSenderDomain })
122
165
  console.log(` per-region foundation deployed (bucket ${bucket}); verifying cross-account trust…`)
166
+ if (emailSenderDomain) {
167
+ const described = JSON.parse(execFileSync('aws', ['cloudformation', 'describe-stacks', '--stack-name', foundationRegionStackName(region), '--region', region, '--output', 'json'], { encoding: 'utf8' }))
168
+ const sender = emailSenderOutputs(described.Stacks[0].Outputs)
169
+ if (sender) logEmailSenderRecords(console.log, emailSenderDomain, sender)
170
+ }
123
171
  const v = await apiCall('POST', '/api/aws/connect/verify', { accountId, region }, flags)
124
172
  console.log(`✅ AWS account ${accountId} connected to org ${orgId} (${v.bootstrapStatus})`)
125
173
  return v
@@ -128,5 +176,6 @@ async function awsConnect(flags) {
128
176
  module.exports = {
129
177
  awsConnect, deployFoundation, foundationDeployArgs, FOUNDATION_TEMPLATE,
130
178
  deployFoundationRegion, foundationRegionDeployArgs, foundationRegionStackName, artifactsBucketName,
179
+ emailSenderDomainFlag, emailSenderOutputs, logEmailSenderRecords,
131
180
  FOUNDATION_REGION_TEMPLATE,
132
181
  }