saaslayer 0.0.2 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,13 +20,13 @@ Requires Node.js >= 18. The `init` command shells out to the [AWS CLI](https://a
20
20
 
21
21
  ### `saaslayer init`
22
22
 
23
- Deploy the host-account bootstrap (3 IAM roles + permissions boundary + artifact bucket) into the caller's AWS account, trusting the SaaSLayer control plane. Uses the bundled `templates/host-account.yml`.
23
+ Deploy the SaaSLayer foundation stack (3 IAM roles + permissions boundary + artifact bucket) into the caller's AWS account, trusting the SaaSLayer control plane. Uses the bundled `templates/saaslayer-foundation.yml`.
24
24
 
25
25
  ```bash
26
26
  saaslayer init \
27
27
  --control-plane-account <12-digit-account-id> \
28
28
  --external-id <secret> \
29
- [--stack-name saaslayer-host-account] \
29
+ [--stack-name saaslayer-foundation] \
30
30
  [--region us-east-1] \
31
31
  [--stack-name-prefix sl-] \
32
32
  [--template PATH] \
@@ -37,7 +37,7 @@ saaslayer init \
37
37
  | --- | --- | --- |
38
38
  | `--control-plane-account` | `SAASLAYER_CONTROL_PLANE_ACCOUNT` | 12-digit AWS account id allowed to assume the deploy role. Required. |
39
39
  | `--external-id` | `SAASLAYER_EXTERNAL_ID` | Trust secret shared during onboarding. Required. |
40
- | `--stack-name` | — | CloudFormation stack name. Defaults to `saaslayer-host-account`. |
40
+ | `--stack-name` | — | CloudFormation stack name. Defaults to `saaslayer-foundation`. |
41
41
  | `--region` | `AWS_REGION` | Deploy region. Defaults to `us-east-1`. |
42
42
  | `--stack-name-prefix` | — | Prefix for provisioned resources. Defaults to `sl-`. |
43
43
  | `--template` | — | Override the bundled template path. |
@@ -58,6 +58,56 @@ saaslayer rbac register ./rbac.manifest.json \
58
58
  | `--api-base` | `SAASLAYER_API_BASE` | RBAC catalog API base URL. Required. |
59
59
  | `--token` | `SAASLAYER_TOKEN` | API key. Required. |
60
60
 
61
+ ### `saaslayer rbac inspect <TYPE>:<id>`
62
+
63
+ Print a principal's permissions (needs `saaslayer:principals` authority over the principal): the assignments table (role, scope,
64
+ direct / inherited / derived, expiry), then `global`, then each scope's allows/denies with the granting role or policy
65
+ and conditions. It always prints size stats: item bytes vs the 340 KB gate, defs, ref sets and scopes. Scopes and
66
+ assignments page independently, and the output ends with copy-paste commands for the next pages. Works the same for
67
+ v1 and v2 (compact) stored docs, because the CLI reads the server's expanded view and never parses the stored format.
68
+
69
+ ```bash
70
+ saaslayer rbac inspect USER:alice --api-base https://api.example.com --token $SAASLAYER_TOKEN
71
+ saaslayer rbac inspect USER:alice --scope org_1 --scope site:org_1:s1 # only these scopes
72
+ saaslayer rbac inspect USER:alice --all-scopes --json > alice.json # every scope page (scripting)
73
+ saaslayer rbac inspect USER:alice --stored # "Stored v1" / "Stored v2 (compact)", problems
74
+ saaslayer rbac inspect session:sess_01abc # a session's stored permission set
75
+ ```
76
+
77
+ | Flag | Description |
78
+ | --- | --- |
79
+ | `--scope S` | Only these scopes (repeatable, at most 50); turns off scope paging. |
80
+ | `--scope-page C` / `--assignment-page C` | The next page (cursors printed by the previous run). A 409 means the doc was rebuilt: restart. |
81
+ | `--all-scopes` | Follow every scope page. Restarts once, with a message, if the doc is rebuilt mid-way. |
82
+ | `--stored` | The stored doc's inspection model: format label, sizes, counts, defs / ref sets or v1 buckets, validation problems. |
83
+ | `--json` | The route payload verbatim. With `--stored`, the raw stored items `{ main, overflow }`. |
84
+ | `--api-base`, `--token` / `--iam` | As for `rbac register`. |
85
+
86
+ The `--token` API key must carry `saaslayer:principals` permissions explicitly; a key without explicit permissions confers none, even when its owner is an admin. Exits 1 with a clear message on 401 / 403 / 404 (no authority, or the principal isn't where you have authority), a bad
87
+ ref, or a missing token.
88
+
61
89
  ## License
62
90
 
63
91
  Proprietary. All rights reserved. See [LICENSE](./LICENSE).
92
+
93
+ ### `saaslayer users export` / `saaslayer users import`
94
+
95
+ Move people from another identity system (today: a Cognito user pool) into a SaaSLayer deployment. It runs locally
96
+ with your own AWS credentials, and nothing passes through SaaSLayer.
97
+
98
+ - **Export** writes a reviewable manifest of accounts, people and roles. Everyone is their account's owner by default.
99
+ - **Import** is a dry run by default. With `--apply` it:
100
+ - imports new users through a Cognito CSV import job. They land reset-required, and no emails are sent; on first
101
+ sign-in `<SignIn>` sends them a reset code.
102
+ - creates each org, adds its members and makes the first Owner.
103
+
104
+ ```bash
105
+ saaslayer users export --provider cognito --user-pool-id us-west-2_SOURCE --region us-west-2 \
106
+ --account-attribute custom:orgId --out manifest.json
107
+ saaslayer users import --manifest manifest.json --user-pool-id us-west-2_TARGET --region us-west-2 # dry run
108
+ saaslayer users import --manifest manifest.json --user-pool-id us-west-2_TARGET --region us-west-2 \
109
+ --api-base https://rbac.example.com --product acme --iam importer --apply # logs role: found from the pool's stack
110
+ ```
111
+
112
+ Prerequisites, the manifest format and how to add a provider (Auth0, Clerk, …) are in
113
+ [docs/users-import.md](../../docs/users-import.md). The manifest holds personal data, so keep it private.
package/bin/saaslayer.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  // SaaSLayer CLI (M0.10, D18) — onboard an AWS account and register RBAC manifests.
3
- // `saaslayer init` deploys the bundled host-account.yml (the control plane's deploy role +
3
+ // `saaslayer init` deploys the bundled saaslayer-foundation.yml (the control plane's deploy role +
4
4
  // boundary + artifact bucket). `saaslayer rbac register` upserts a service's rbac.manifest.json
5
5
  // into the RBAC catalog (POST /catalog/register) — run by a human or wired into CI.
6
6
 
@@ -17,7 +17,11 @@ function parseArgs(argv) {
17
17
  if (a.startsWith('--')) {
18
18
  const key = a.slice(2)
19
19
  const next = argv[i + 1]
20
- if (next === undefined || next.startsWith('--')) { flags[key] = true } else { flags[key] = next; i++ }
20
+ if (next === undefined || next.startsWith('--')) { flags[key] = true } else {
21
+ // A repeated value flag (e.g. --scope a --scope b) collects every value in order
22
+ flags[key] = typeof flags[key] === 'string' ? [flags[key], next] : Array.isArray(flags[key]) ? [...flags[key], next] : next
23
+ i++
24
+ }
21
25
  } else { positional.push(a) }
22
26
  }
23
27
  return { positional, flags }
@@ -27,46 +31,118 @@ const HELP = `saaslayer — SaaSLayer onboarding CLI
27
31
 
28
32
  Usage:
29
33
  saaslayer init --control-plane-account <12-digit> --external-id <secret> [--stack-name NAME]
30
- [--region REGION] [--stack-name-prefix sl-] [--template PATH] [--dry-run]
34
+ [--region REGION] [--stack-name-prefix sl-] [--org-id ID] [--template PATH] [--dry-run]
31
35
  Deploy the SaaSLayer foundation stack (3 IAM roles + permissions boundary + artifact
32
36
  bucket) into the caller's AWS account, trusting the SaaSLayer control plane.
33
- Uses the bundled templates/host-account.yml. --dry-run validates only.
37
+ Uses the bundled templates/saaslayer-foundation.yml. --dry-run validates only.
34
38
 
35
- saaslayer rbac register <manifest.json> --api-base URL [--token KEY]
36
- Upsert a service's rbac.manifest.json into the RBAC catalog.
37
- --token defaults to $SAASLAYER_TOKEN.
39
+ saaslayer signup --config-url URL [--email E --password P]
40
+ Create a SaaSLayer account (allowlist-gated) and log in.
41
+ saaslayer login [--email E --password P] [--config-url URL | --user-pool-id ID --client-id ID --region R]
42
+ Log in to your SaaSLayer account (Cognito SRP) and cache tokens in ~/.saaslayer.
43
+ Email/password fall back to $SAASLAYER_EMAIL/$SAASLAYER_PASSWORD, else prompt.
44
+ saaslayer whoami Show the current logged-in account.
45
+ saaslayer accounts List all cached accounts (most-recently-used first; * = active).
46
+ saaslayer account use <email> Switch the active account to another cached login (no re-auth).
47
+ saaslayer logout [--user <email|userId>] Clear the current cached account (or the named one).
48
+
49
+ saaslayer rbac register <manifest.json> --product PRODUCT --api-base URL (--iam PRINCIPAL | --token KEY)
50
+ Upsert a service's rbac.manifest.json into the RBAC catalog under the product that owns it (a service
51
+ belongs to exactly one product; --product defaults to the manifest's "product"). Publishes a new registry
52
+ snapshot version, live in every container within 60 s. --token defaults to $SAASLAYER_TOKEN.
53
+ saaslayer rbac inspect <TYPE>:<id> --api-base URL (--iam PRINCIPAL | --token KEY) [--scope S]... [--scope-page C]
54
+ [--assignment-page C] [--all-scopes] [--stored] [--json]
55
+ Print a principal's permissions (needs saaslayer:principals read): assignments, global and per-scope allows/denies with the
56
+ granting role/policy and conditions, size stats (item bytes vs the 340 KB gate, defs, ref sets, scopes) and
57
+ copy-paste next-page commands. --all-scopes follows every scope page (restarts once if the doc is rebuilt
58
+ mid-way). --stored prints the stored doc's inspection model ("Stored v1" / "Stored v2 (compact)", problems);
59
+ --stored --json the raw stored items. session:<id> inspects a session's stored permission set.
60
+ saaslayer catalog apply <catalog.json> --api-base URL (--iam PRINCIPAL [--region R] [--profile P] | --token KEY)
61
+ [--dry-run] [--allow-orphan] [--adopt]
62
+ Apply a product's versioned role catalog (managed system roles) to its RBAC API.
63
+ --iam authenticates as one of your IAM principals using your AWS credentials.
64
+ --dry-run prints the plan and role diff without writing; --allow-orphan permits
65
+ removing roles that still have assignments; --adopt converts org-owned roles with catalog
66
+ ids into shared catalog roles (assignments kept). Fails if the manifest's selfCheck fails.
67
+ saaslayer catalog export --snapshot --out FILE --api-base URL (--iam PRINCIPAL | --token KEY)
68
+ Write the currently published registry snapshot ({ meta, snapshot }) to FILE — the pinned registry
69
+ rbac-node direct mode loads at deploy.
70
+ saaslayer catalog get <product> --api-base URL (--iam PRINCIPAL [--region R] [--profile P] | --token KEY)
71
+ Print the catalog currently applied for a product (version, content hash, roles, manifest).
72
+ saaslayer catalog bootstrap-owner <product> --org ORG --user USER --api-base URL (--iam PRINCIPAL | --token KEY)
73
+ Make a member the FIRST owner of an org (refused once the org has an owner). Needs owners:bootstrap.
74
+ saaslayer catalog reconcile-owners <product> --api-base URL (--iam PRINCIPAL | --token KEY) [--org ORG] [--apply]
75
+ Compare each org's owner counter with a live recount; --apply repairs drift.
76
+ saaslayer rbac iam-principals set <principals.json> --deployment DEP --region R [--profile P] [--service-instance I]
77
+ saaslayer rbac iam-principals get --deployment DEP --region R [--profile P] [--service-instance I]
78
+ Declare which of your AWS IAM roles are trusted RBAC principals and their credential
79
+ scopes (catalog:read, catalog:write, owners:bootstrap, orgs:read, orgs:write, users:write, broker:<product>). Written to SSM in YOUR
80
+ account with your AWS creds:
81
+ { "principals": [{ "principalId": "ci", "roleArn": "arn:aws:iam::…:role/…", "scopes": ["catalog:write"] }] }
82
+
83
+ saaslayer users export --provider cognito --user-pool-id POOL --region R [--profile P]
84
+ [--account-attribute ATTR] [--account-name-attribute ATTR] [--role-map map.js] --out manifest.json
85
+ Read users from another identity system with YOUR credentials into a reviewable manifest (accounts → people →
86
+ role; everyone is their account's owner unless --role-map says otherwise). Providers: cognito. No secrets are
87
+ exported; the file holds personal data.
88
+ saaslayer users import --manifest manifest.json --user-pool-id POOL --region R [--profile P]
89
+ [--api-base URL --product P (--iam PRINCIPAL | --token KEY) [--logs-role-arn ARN] --apply] [--report FILE]
90
+ Dry run by default: prints what would be created or linked. --apply imports new users through a Cognito CSV
91
+ import job (reset required on first sign-in, no emails sent), stamps their SaaSLayer id + default org, then
92
+ creates each user's rbac principal and org, adds members and bootstraps the first Owner (IAM scopes users:write + orgs:write + owners:bootstrap).
93
+ Idempotent: re-run to retry failures. See docs/users-import.md.
94
+
95
+ Deploy & lifecycle (requires login + a connected AWS account):
96
+ saaslayer aws connect --aws-account <id> [--region R] [--org ID] [--org-wide]
97
+ Connect your AWS account to an org. Binds it to your active project by
98
+ default; --org-wide lets any project in the org deploy into it.
99
+ saaslayer project use <id> Set the active project for deploy/status.
100
+ saaslayer stacks List the vendable stacks a project can deploy.
101
+ saaslayer deploy [--services a,b] [--env prod] [--region R] [--target ACCT]
102
+ [--commit-sha SHA] [--admin-email E] [--yes]
103
+ Deploy the project's services into your connected account. Shows a cost
104
+ estimate and asks to confirm (skip with --yes).
105
+ saaslayer status [--project ID] [--region R]
106
+ Show the deployed instances of a project.
107
+ saaslayer service add <service> [--region R]
108
+ saaslayer service remove <service> --data-custody delete|retain [--region R]
109
+ Add or remove a single service on an existing deployment.
110
+ saaslayer update --commit-sha SHA [--param SVC.Param=VALUE ...] [--env E] [--region R] [--reason TEXT] [--force]
111
+ Roll an existing deployment's services to a new commit (upgrade; deploy only creates), and/or change
112
+ update-safe settings with --param (repeatable; without --commit-sha the current commit is kept), e.g.
113
+ --param user-service.AllowedAppOrigins=https://app.example.com. Protected envs (staging, prod) need
114
+ --reason; --force updates past the drift gate (audited with the reason).
115
+ saaslayer destroy --data-custody delete|retain [--region R] [--yes]
116
+ Tear down the project's deployment (typed-name confirmation).
117
+
118
+ Data migrations you run yourself (a deployment with migrationRunner self):
119
+ saaslayer migrate status --deployment <id> [--service <ref>]
120
+ saaslayer migrate plan --deployment <id> [--service <ref>]
121
+ saaslayer migrate dry-run --deployment <id> [--service <ref>]
122
+ saaslayer migrate up --deployment <id> [--service <ref>] [--approve-destructive --reason <text>]
123
+ saaslayer migrate report --deployment <id> [--service <ref>]
124
+ Run each service's migrations with YOUR AWS credentials (default chain or --profile; aws CLI v2), assuming the
125
+ service's migrate role (your principal must be in migrateTrustedPrincipalArns). The checkout (--repo, default cwd)
126
+ must be at each service's deployed commit. up reports each service's ledger to SaaSLayer; report re-sends it from
127
+ the ledger (read-only) after a lost report. Also: --repo <path> --profile <p> --json.
128
+ An UPDATE blocked with MIGRATION_PENDING_SELF_RUN: check out its target commit and run migrate up; only the
129
+ pre-deploy migrations run, and the report that completes them resumes the update.
130
+ Standalone (no control plane, no report): --stack <stackName> --region <r>, with --repo the service dir.
131
+ Exit codes: 0 ok / up-to-date, 1 failed, 2 awaiting approval, 3 applied but not reported.
38
132
 
39
133
  Global:
40
134
  --help Show this help.`
41
135
 
42
- async function cmdRegister({ positional, flags }) {
43
- const manifestPath = positional[0]
44
- if (!manifestPath) throw new Error('rbac register: a manifest path is required')
45
- const apiBase = flags['api-base'] || process.env.SAASLAYER_API_BASE
46
- const token = flags.token || process.env.SAASLAYER_TOKEN
47
- if (!apiBase) throw new Error('rbac register: --api-base (or $SAASLAYER_API_BASE) is required')
48
- if (!token) throw new Error('rbac register: --token (or $SAASLAYER_TOKEN) is required')
49
- const manifest = JSON.parse(fs.readFileSync(path.resolve(manifestPath), 'utf8'))
50
- const res = await fetch(`${apiBase.replace(/\/$/, '')}/catalog/register`, {
51
- method: 'POST',
52
- headers: { 'x-api-key': token, authorization: `Bearer ${token}`, 'content-type': 'application/json' },
53
- body: JSON.stringify(manifest),
54
- })
55
- const body = await res.json().catch(() => ({}))
56
- if (!res.ok) throw new Error(`register failed (${res.status}): ${JSON.stringify(body.errors || body)}`)
57
- const a = body.data && body.data.attributes
58
- console.log(`registered "${(a && a.service) || manifest.service}" (${(a && a.resourceCount) || '?'} resource types)`)
59
- }
60
-
61
136
  function cmdInit({ flags }) {
62
- const template = flags.template || path.join(__dirname, '..', 'templates', 'host-account.yml')
137
+ const template = flags.template || path.join(__dirname, '..', 'templates', 'saaslayer-foundation.yml')
63
138
  if (!fs.existsSync(template)) throw new Error(`init: template not found at ${template}`)
64
139
  const region = flags.region || process.env.AWS_REGION || 'us-east-1'
65
140
  // Canonical name — the account-global named IAM resources allow only one SaaSLayer
66
141
  // foundation stack per account, so init always updates the same stack.
67
142
  const stackName = flags['stack-name'] || 'saaslayer-foundation'
143
+ const { writeDeployableTemplate, initDeployArgs, redactArgs } = require('../src/foundation-template')
68
144
  if (flags['dry-run']) {
69
- execFileSync('aws', ['cloudformation', 'validate-template', '--template-body', `file://${template}`, '--region', region], { stdio: 'inherit' })
145
+ execFileSync('aws', ['cloudformation', 'validate-template', '--template-body', `file://${writeDeployableTemplate(template)}`, '--region', region], { stdio: 'inherit' })
70
146
  console.log(`\n[dry-run] template valid. Would deploy stack "${stackName}" to ${region}.`)
71
147
  return
72
148
  }
@@ -75,16 +151,18 @@ function cmdInit({ flags }) {
75
151
  const controlPlaneAccount = flags['control-plane-account'] || process.env.SAASLAYER_CONTROL_PLANE_ACCOUNT
76
152
  const externalId = flags['external-id'] || process.env.SAASLAYER_EXTERNAL_ID
77
153
  const stackPrefix = flags['stack-name-prefix'] || 'sl-'
154
+ const orgId = flags['org-id'] || process.env.SAASLAYER_ORG_ID || ''
78
155
  if (!controlPlaneAccount) throw new Error('init: --control-plane-account <12-digit id> (or $SAASLAYER_CONTROL_PLANE_ACCOUNT) is required')
79
156
  if (!/^[0-9]{12}$/.test(controlPlaneAccount)) throw new Error('init: --control-plane-account must be a 12-digit AWS account id')
80
157
  if (!externalId) throw new Error('init: --external-id <secret> (or $SAASLAYER_EXTERNAL_ID) is required — shared during onboarding')
81
158
  console.log(`Deploying SaaSLayer foundation stack "${stackName}" to ${region} (control plane ${controlPlaneAccount})…`)
82
- execFileSync('aws', [
83
- 'cloudformation', 'deploy', '--template-file', template, '--stack-name', stackName, '--region', region,
84
- '--capabilities', 'CAPABILITY_NAMED_IAM',
85
- '--parameter-overrides',
86
- `ControlPlaneAccountId=${controlPlaneAccount}`, `ExternalId=${externalId}`, `StackNamePrefix=${stackPrefix}`,
87
- ], { stdio: 'inherit' })
159
+ const args = initDeployArgs({ template, stackName, region, controlPlaneAccount, externalId, stackPrefix, orgId })
160
+ try {
161
+ execFileSync('aws', args, { stdio: 'inherit' })
162
+ } catch (err) {
163
+ // execFileSync's message echoes the full argv; never let the ExternalId reach the terminal or logs.
164
+ throw new Error(`init: aws ${redactArgs(args).join(' ')} failed (exit ${err.status ?? '?'})`)
165
+ }
88
166
  console.log('\nSaaSLayer foundation deployed.')
89
167
  console.log(` • Control plane ${controlPlaneAccount} may now assume the deploy role (ExternalId gated).`)
90
168
  console.log(` • It can manage only CloudFormation stacks named "${stackPrefix}*" in this account.`)
@@ -98,7 +176,114 @@ async function main() {
98
176
  const [cmd, sub] = positional
99
177
  try {
100
178
  if (cmd === 'init') return cmdInit({ flags })
101
- if (cmd === 'rbac' && sub === 'register') return await cmdRegister({ positional: positional.slice(2), flags })
179
+ if (cmd === 'rbac' && sub === 'inspect') { await require('../src/commands/rbac-inspect').rbacInspect(positional.slice(2), flags); return }
180
+ if (cmd === 'rbac' && sub === 'register') { await require('../src/commands/catalog').rbacRegister(positional.slice(2), flags); return }
181
+ if (cmd === 'catalog' && sub === 'apply') { await require('../src/commands/catalog').catalogApply(positional.slice(2), flags); return }
182
+ if (cmd === 'catalog' && sub === 'bootstrap-owner') { const a = await require('../src/commands/catalog').catalogBootstrapOwner(positional.slice(2), flags); console.log(`${a.userId} is now ${a.roleId} of ${a.scope}`); return }
183
+ if (cmd === 'catalog' && sub === 'reconcile-owners') {
184
+ const r = await require('../src/commands/catalog').catalogReconcileOwners(positional.slice(2), flags)
185
+ for (const o of r.orgs) console.log(`${o.ok ? 'ok ' : 'DRIFT'} ${o.orgId} counter=${o.counter} actual=${o.actual}`)
186
+ console.log(r.applied ? 'repaired mismatched counters' : 'report only (pass --apply to repair)')
187
+ return
188
+ }
189
+ if (cmd === 'catalog' && sub === 'export') { await require('../src/commands/catalog').catalogExport(positional.slice(2), flags); return }
190
+ if (cmd === 'catalog' && sub === 'get') { console.log(JSON.stringify(await require('../src/commands/catalog').catalogGet(positional.slice(2), flags), null, 2)); return }
191
+ if (cmd === 'rbac' && sub === 'iam-principals') {
192
+ const iamp = require('../src/commands/iam-principals')
193
+ if (positional[2] === 'set') { const name = iamp.iamPrincipalsSet(positional.slice(3), flags); console.log(`wrote ${name} (takes effect within ~60s)`); return }
194
+ if (positional[2] === 'get') { console.log(JSON.stringify(iamp.iamPrincipalsGet(positional.slice(3), flags), null, 2)); return }
195
+ console.error('usage: saaslayer rbac iam-principals <set <file>|get> --deployment DEP --region R'); process.exit(1)
196
+ }
197
+ if (cmd === 'users') {
198
+ const users = require('../src/commands/users')
199
+ if (sub === 'export') { await users.usersExport(flags); return }
200
+ if (sub === 'import') { await users.usersImport(flags); return }
201
+ console.error('usage: saaslayer users <export|import> … (see saaslayer --help)'); process.exit(1)
202
+ }
203
+ if (cmd === 'signup') {
204
+ const { signup } = require('../src/commands/login')
205
+ const who = await signup(flags)
206
+ console.log(`account created — logged in as ${who.email}`)
207
+ return
208
+ }
209
+ if (cmd === 'login') {
210
+ const { login } = require('../src/commands/login')
211
+ const who = await login(flags)
212
+ console.log(`logged in as ${who.email}`)
213
+ return
214
+ }
215
+ if (cmd === 'logout') {
216
+ const { logout } = require('../src/commands/login')
217
+ logout(flags)
218
+ console.log('logged out')
219
+ return
220
+ }
221
+ if (cmd === 'whoami') {
222
+ const { whoami } = require('../src/commands/login')
223
+ const who = whoami()
224
+ if (!who) { console.log('not logged in'); return }
225
+ console.log(`${who.email} (${who.env})`)
226
+ return
227
+ }
228
+ if (cmd === 'accounts' || (cmd === 'account' && (sub === 'list' || sub === undefined))) {
229
+ const { accountsList } = require('../src/commands/accounts')
230
+ const rows = accountsList()
231
+ if (!rows.length) { console.log('no cached accounts — run `saaslayer login`'); return }
232
+ for (const r of rows) {
233
+ const marker = r.current ? '*' : ' '
234
+ const expired = r.expired === true ? ' (token expired — run `saaslayer login`)' : ''
235
+ console.log(`${marker} ${r.email} [${r.env}]${expired}`)
236
+ }
237
+ console.log('\n* = active. Switch with: saaslayer account use <email>')
238
+ return
239
+ }
240
+ if (cmd === 'account' && sub === 'use') {
241
+ const { accountUse } = require('../src/commands/accounts')
242
+ const who = accountUse(positional[2])
243
+ console.log(`active account: ${who.email} (${who.env})`)
244
+ return
245
+ }
246
+ if (cmd === 'org') {
247
+ const orgs = require('../src/commands/orgs')
248
+ if (sub === 'create') { const o = await orgs.orgCreate(flags, positional[2]); console.log(`created org ${o.name || ''} (${o.id}) — now active`); return }
249
+ 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 }
250
+ if (sub === 'use') { const id = orgs.orgUse(flags, positional[2]); console.log(`active org: ${id}`); return }
251
+ console.error('usage: saaslayer org <create|list|use> …'); process.exit(1)
252
+ }
253
+ if (cmd === 'project') {
254
+ const orgs = require('../src/commands/orgs')
255
+ if (sub === 'create') { const p = await orgs.projectCreate(flags, positional[2]); console.log(`created project ${p.name || ''} (${p.id}) in org ${p.orgId}`); return }
256
+ if (sub === 'use') { const id = positional[2]; if (!id) throw new Error('project use requires a project id'); require('../src/context-store').set('project', id); console.log(`active project: ${id}`); return }
257
+ console.error('usage: saaslayer project <create <name>|use <id>>'); process.exit(1)
258
+ }
259
+ if (cmd === 'projects') {
260
+ const orgs = require('../src/commands/orgs')
261
+ const list = await orgs.projectList(flags)
262
+ if (!list.length) console.log('no projects'); else list.forEach((p) => console.log(`${p.id}${p.name ? ' ' + p.name : ''}`))
263
+ return
264
+ }
265
+ if (cmd === 'aws') {
266
+ const aws = require('../src/commands/aws')
267
+ if (sub === 'connect') { await aws.awsConnect(flags); return }
268
+ console.error('usage: saaslayer aws connect --aws-account <id> [--region <r>] [--org-wide]'); process.exit(1)
269
+ }
270
+ if (cmd === 'stacks') { const { stacks } = require('../src/commands/stacks'); await stacks(flags); return }
271
+ if (cmd === 'deploy') { const { deploy } = require('../src/commands/deploy'); await deploy(flags); return }
272
+ if (cmd === 'status') { const { status } = require('../src/commands/lifecycle'); await status(flags); return }
273
+ if (cmd === 'update') { const { update } = require('../src/commands/lifecycle'); await update(flags); return }
274
+ if (cmd === 'destroy') { const { destroy } = require('../src/commands/lifecycle'); await destroy(flags); return }
275
+ if (cmd === 'migrate') {
276
+ const { migrate } = require('../src/commands/migrate')
277
+ const result = await migrate(sub, flags)
278
+ process.exitCode = result.exitCode
279
+ return
280
+ }
281
+ if (cmd === 'service') {
282
+ const lc = require('../src/commands/lifecycle')
283
+ if (sub === 'add') { await lc.serviceAdd(positional[2], flags); return }
284
+ if (sub === 'remove') { await lc.serviceRemove(positional[2], flags); return }
285
+ console.error('usage: saaslayer service <add|remove> <service> [--data-custody delete|retain]'); process.exit(1)
286
+ }
102
287
  console.error(`Unknown command: ${positional.join(' ')}\n`); console.log(HELP); process.exit(1)
103
288
  } catch (err) {
104
289
  console.error(`error: ${err.message}`); process.exit(1)
package/package.json CHANGED
@@ -1,14 +1,16 @@
1
1
  {
2
2
  "name": "saaslayer",
3
- "version": "0.0.2",
4
- "description": "SaaSLayer CLI — onboard an account (init) and register a service's RBAC manifest.",
3
+ "version": "0.0.7",
4
+ "description": "SaaSLayer CLI \u2014 onboard an account (init) and register a service's RBAC manifest.",
5
5
  "type": "commonjs",
6
6
  "bin": {
7
7
  "saaslayer": "bin/saaslayer.js"
8
8
  },
9
9
  "files": [
10
10
  "bin",
11
+ "src",
11
12
  "templates",
13
+ "vendor",
12
14
  "README.md",
13
15
  "LICENSE"
14
16
  ],
@@ -38,11 +40,23 @@
38
40
  "access": "public"
39
41
  },
40
42
  "scripts": {
41
- "test": "node bin/saaslayer.js --help >/dev/null && echo ok",
43
+ "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/catalog.test.js && node test/catalog-registry.test.js && node test/rbac-inspect.test.js && node test/iam.test.js && node test/iam-principals.test.js && node test/package-files.test.js && node test/users-export.test.js && node test/users-import.test.js && node test/migrate.test.js && node test/foundation-template.test.js && echo ok",
42
44
  "sync-template": "node scripts/sync-template.js",
45
+ "sync-template:check": "node scripts/sync-template.js --check",
43
46
  "prepublishOnly": "node scripts/sync-template.js",
44
47
  "release:patch": "npm version patch && npm publish",
45
48
  "release:minor": "npm version minor && npm publish",
46
- "release:major": "npm version major && npm publish"
49
+ "release:major": "npm version major && npm publish",
50
+ "test:ddb": "node test/migrate.ddb.test.js",
51
+ "prepack": "node scripts/sync-vendor.js",
52
+ "sync-vendor": "node scripts/sync-vendor.js"
53
+ },
54
+ "dependencies": {
55
+ "@aws-sdk/client-dynamodb": "^3.700.0",
56
+ "@aws-sdk/client-sts": "^3.1058.0",
57
+ "@aws-sdk/lib-dynamodb": "^3.700.0",
58
+ "@davidwells/cogneato": "^0.6.0",
59
+ "@davidwells/smart-log": "^1.0.0",
60
+ "ddb-migration-tools": "^2.7.0"
47
61
  }
48
62
  }
@@ -0,0 +1,71 @@
1
+ // Authenticated calls to the SaaSLayer control-plane API using the cached Cognito id token (Bearer).
2
+ // Shared by the org/project/aws commands.
3
+ 'use strict'
4
+ const creds = require('./credentials')
5
+ const { resolvePoolConfig } = require('./config')
6
+
7
+ function apiBase(flags = {}) {
8
+ const base = flags['config-url'] || process.env.SAASLAYER_CONFIG_URL
9
+ if (!base) throw new Error('control-plane API base required: pass --config-url or set $SAASLAYER_CONFIG_URL')
10
+ return String(base).replace(/\/$/, '')
11
+ }
12
+
13
+ // Refresh a little before expiry so a token never lapses mid-request.
14
+ const REFRESH_SKEW_SECONDS = 60
15
+
16
+ function bearer() {
17
+ const current = creds.getCurrent()
18
+ if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
19
+ return current.idToken
20
+ }
21
+
22
+ /**
23
+ * Exchange the stored refresh token for fresh id/access tokens (Cognito REFRESH_TOKEN_AUTH) and persist them.
24
+ * The refresh token itself is not rotated by Cognito, so it is kept.
25
+ * @param {object} current the cached account record
26
+ * @param {object} flags
27
+ */
28
+ async function refreshTokens(current, flags) {
29
+ const pool = await resolvePoolConfig(flags)
30
+ const res = await fetch(`https://cognito-idp.${pool.region}.amazonaws.com/`, {
31
+ method: 'POST',
32
+ headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'AWSCognitoIdentityProviderService.InitiateAuth' },
33
+ body: JSON.stringify({ AuthFlow: 'REFRESH_TOKEN_AUTH', ClientId: pool.clientId, AuthParameters: { REFRESH_TOKEN: current.refreshToken } }),
34
+ })
35
+ const doc = await res.json().catch(() => ({}))
36
+ const result = doc && doc.AuthenticationResult
37
+ if (!res.ok || !result || !result.IdToken) throw new Error('session expired — run `saaslayer login`')
38
+ return creds.setUser({
39
+ ...current,
40
+ idToken: result.IdToken,
41
+ accessToken: result.AccessToken || current.accessToken,
42
+ expiresAt: Math.floor(Date.now() / 1000) + (Number(result.ExpiresIn) || 3600),
43
+ })
44
+ }
45
+
46
+ /**
47
+ * The current id token, refreshed first when it is expired (or about to be).
48
+ * @param {object} [flags]
49
+ */
50
+ async function freshBearer(flags = {}) {
51
+ const current = creds.getCurrent()
52
+ if (!current || !current.idToken) throw new Error('not logged in — run `saaslayer login` first')
53
+ const now = Math.floor(Date.now() / 1000)
54
+ if (!current.expiresAt || current.expiresAt - REFRESH_SKEW_SECONDS > now) return current.idToken
55
+ if (!current.refreshToken) throw new Error('session expired — run `saaslayer login`')
56
+ return (await refreshTokens(current, flags)).idToken
57
+ }
58
+
59
+ async function apiCall(method, path, body, flags) {
60
+ const token = await freshBearer(flags)
61
+ const res = await fetch(`${apiBase(flags)}${path}`, {
62
+ method,
63
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
64
+ body: body === undefined ? undefined : JSON.stringify(body),
65
+ })
66
+ const doc = await res.json().catch(() => ({}))
67
+ if (!res.ok) throw new Error(`${method} ${path} failed (${res.status}): ${doc.error || JSON.stringify(doc)}`)
68
+ return doc
69
+ }
70
+
71
+ module.exports = { apiBase, bearer, freshBearer, apiCall }
@@ -0,0 +1,47 @@
1
+ // AWS Signature Version 4 request signing (no SDK dependency): signs every provided header plus x-amz-date and,
2
+ // with temporary credentials, x-amz-security-token. Used to build the STS proof for the rbac IAM exchange.
3
+ 'use strict'
4
+ const crypto = require('crypto')
5
+
6
+ const sha256 = (data) => crypto.createHash('sha256').update(data, 'utf8').digest('hex')
7
+ const hmac = (key, data) => crypto.createHmac('sha256', key).update(data, 'utf8').digest()
8
+ const encode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
9
+
10
+ /**
11
+ * @param {{ method: string, url: string, headers: Record<string, string>, body: string, region: string, service: string,
12
+ * credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date }} req
13
+ * @returns {{ headers: Record<string, string> }} the input headers plus X-Amz-Date, X-Amz-Security-Token and Authorization
14
+ */
15
+ function signRequest({ method, url, headers, body, region, service, credentials, now = new Date() }) {
16
+ const amzDate = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
17
+ const date = amzDate.slice(0, 8)
18
+ const out = { ...headers, 'X-Amz-Date': amzDate }
19
+ if (credentials.sessionToken) out['X-Amz-Security-Token'] = credentials.sessionToken
20
+
21
+ const u = new URL(url)
22
+ const query = [...u.searchParams.entries()]
23
+ .map(([k, v]) => [encode(k), encode(v)])
24
+ .sort((a, b) => (a[0] === b[0] ? a[1].localeCompare(b[1]) : a[0] < b[0] ? -1 : 1))
25
+ .map(([k, v]) => `${k}=${v}`)
26
+ .join('&')
27
+ const canonical = Object.entries(out)
28
+ .map(([k, v]) => [k.toLowerCase(), String(v).trim().replace(/\s+/g, ' ')])
29
+ .sort((a, b) => (a[0] < b[0] ? -1 : 1))
30
+ const signedHeaders = canonical.map(([k]) => k).join(';')
31
+ const canonicalRequest = [
32
+ method.toUpperCase(),
33
+ u.pathname || '/',
34
+ query,
35
+ canonical.map(([k, v]) => `${k}:${v}\n`).join(''),
36
+ signedHeaders,
37
+ sha256(body || ''),
38
+ ].join('\n')
39
+ const scope = `${date}/${region}/${service}/aws4_request`
40
+ const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256(canonicalRequest)].join('\n')
41
+ const key = hmac(hmac(hmac(hmac(`AWS4${credentials.secretAccessKey}`, date), region), service), 'aws4_request')
42
+ const signature = crypto.createHmac('sha256', key).update(stringToSign, 'utf8').digest('hex')
43
+ out.Authorization = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
44
+ return { headers: out }
45
+ }
46
+
47
+ module.exports = { signRequest }
@@ -0,0 +1,25 @@
1
+ // `saaslayer accounts | account list | account use <email>` — inspect and switch between the SaaSLayer
2
+ // accounts cached locally, so a user with several logins can move between them without re-authenticating.
3
+ 'use strict'
4
+ const creds = require('../credentials')
5
+
6
+ // All cached accounts, most-recently-used first, flagging the active one and whether its token is expired.
7
+ function accountsList() {
8
+ const current = creds.getCurrent()
9
+ const now = Math.floor(Date.now() / 1000)
10
+ return creds.list().map((u) => ({
11
+ userId: u.userId,
12
+ email: u.email,
13
+ env: u.env,
14
+ current: current ? u.userId === current.userId : false,
15
+ expired: typeof u.expiresAt === 'number' ? u.expiresAt <= now : null,
16
+ }))
17
+ }
18
+
19
+ // Switch the active account to `selector` (an email or userId). Returns the now-current account.
20
+ function accountUse(selector) {
21
+ if (!selector) throw new Error('account use requires an <email> or <userId>')
22
+ return creds.setCurrent(selector)
23
+ }
24
+
25
+ module.exports = { accountsList, accountUse }