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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "saaslayer",
3
- "version": "0.2.0",
3
+ "version": "0.4.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/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 && 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/versions.test.js && node test/migrations-approve.test.js && node test/service-add.test.js && node test/service-remove.test.js && node test/destroy.test.js && node test/settings.test.js && node test/login-methods.test.js && node test/settings-login-domain.test.js && node test/login-domain.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/support-staff.test.js && node test/permission-orgs.test.js && node test/first-admin.test.js && node test/social.test.js && node test/hooks.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-import-checkpoint.test.js && node test/users-import-profiles.test.js && node test/users.test.js && node test/users-api.test.js && node test/migrate.test.js && node test/foundation-template.test.js && node test/trust-entries.test.js && node test/foundation-home.test.js && node test/foundation.test.js && node test/foundation-change-set.test.js && node test/foundation-trust-write.test.js && node test/connection-proof.test.js && node test/aws-connect.test.js && node test/aws-rotate-trust.test.js && node test/sms-setup.test.js && node test/sms-release.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 && node test/sms-register.test.js && node test/sms-status.test.js && echo ok && node test/id-token-auth.test.js && node test/trust-policies.test.js && node test/api-keys.test.js && node test/bindings.test.js && node test/binding-handoff.test.js && node test/env-export.test.js && node test/audit-erase.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",
@@ -54,6 +54,7 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@aws-sdk/client-dynamodb": "^3.700.0",
57
+ "@aws-sdk/client-pinpoint-sms-voice-v2": "^3.1147.0",
57
58
  "@aws-sdk/client-sts": "^3.1058.0",
58
59
  "@aws-sdk/lib-dynamodb": "^3.700.0",
59
60
  "@davidwells/cogneato": "^0.6.0",
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 }
package/src/aws-sigv4.js CHANGED
@@ -1,5 +1,5 @@
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 permissions IAM exchange.
1
+ // AWS Signature Version 4 request signing (no SDK dependency): header signing (the STS proof for the permissions IAM
2
+ // exchange) and query-string presigning (the org connection proof of `saaslayer aws connect`).
3
3
  'use strict'
4
4
  const crypto = require('crypto')
5
5
 
@@ -7,41 +7,89 @@ const sha256 = (data) => crypto.createHash('sha256').update(data, 'utf8').digest
7
7
  const hmac = (key, data) => crypto.createHmac('sha256', key).update(data, 'utf8').digest()
8
8
  const encode = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
9
9
 
10
+ /** @param {Date} now @returns {{ amzDate: string, date: string }} */
11
+ function stamp(now) {
12
+ const amzDate = now.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
13
+ return { amzDate, date: amzDate.slice(0, 8) }
14
+ }
15
+
16
+ /**
17
+ * The canonical query string: every name and value URI-encoded, sorted by name then value.
18
+ * @param {Array<[string, string]>} entries
19
+ */
20
+ function canonicalQuery(entries) {
21
+ return entries
22
+ .map(([k, v]) => [encode(k), encode(v)])
23
+ .sort((a, b) => (a[0] === b[0] ? a[1].localeCompare(b[1]) : a[0] < b[0] ? -1 : 1))
24
+ .map(([k, v]) => `${k}=${v}`)
25
+ .join('&')
26
+ }
27
+
28
+ /**
29
+ * Canonical headers (lowercased, trimmed, sorted) and the signed-headers list.
30
+ * @param {Record<string, string>} headers
31
+ */
32
+ function canonicalHeaders(headers) {
33
+ const canonical = Object.entries(headers)
34
+ .map(([k, v]) => [k.toLowerCase(), String(v).trim().replace(/\s+/g, ' ')])
35
+ .sort((a, b) => (a[0] < b[0] ? -1 : 1))
36
+ return { text: canonical.map(([k, v]) => `${k}:${v}\n`).join(''), signedHeaders: canonical.map(([k]) => k).join(';') }
37
+ }
38
+
39
+ /**
40
+ * The SigV4 signature of a canonical request.
41
+ * @param {{ canonicalRequest: string, amzDate: string, scope: string, date: string, region: string, service: string, secretAccessKey: string }} o
42
+ */
43
+ function signature({ canonicalRequest, amzDate, scope, date, region, service, secretAccessKey }) {
44
+ const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256(canonicalRequest)].join('\n')
45
+ const key = hmac(hmac(hmac(hmac(`AWS4${secretAccessKey}`, date), region), service), 'aws4_request')
46
+ return crypto.createHmac('sha256', key).update(stringToSign, 'utf8').digest('hex')
47
+ }
48
+
10
49
  /**
11
50
  * @param {{ method: string, url: string, headers: Record<string, string>, body: string, region: string, service: string,
12
51
  * credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date }} req
13
52
  * @returns {{ headers: Record<string, string> }} the input headers plus X-Amz-Date, X-Amz-Security-Token and Authorization
14
53
  */
15
54
  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)
55
+ const { amzDate, date } = stamp(now)
18
56
  const out = { ...headers, 'X-Amz-Date': amzDate }
19
57
  if (credentials.sessionToken) out['X-Amz-Security-Token'] = credentials.sessionToken
20
58
 
21
59
  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')
60
+ const { text, signedHeaders } = canonicalHeaders(out)
61
+ const canonicalRequest = [method.toUpperCase(), u.pathname || '/', canonicalQuery([...u.searchParams.entries()]), text, signedHeaders, sha256(body || '')].join('\n')
39
62
  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}`
63
+ const sig = signature({ canonicalRequest, amzDate, scope, date, region, service, secretAccessKey: credentials.secretAccessKey })
64
+ out.Authorization = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${signedHeaders}, Signature=${sig}`
44
65
  return { headers: out }
45
66
  }
46
67
 
47
- module.exports = { signRequest }
68
+ /**
69
+ * A query-string presigned URL: the request's own query plus the X-Amz-* authentication parameters, signing `host` and
70
+ * every given header (which the executor must send unchanged). The URL carries credentials: never log it.
71
+ * @param {{ method?: string, url: string, headers?: Record<string, string>, region: string, service: string, expires: number,
72
+ * credentials: { accessKeyId: string, secretAccessKey: string, sessionToken?: string }, now?: Date, payloadHash?: string }} req
73
+ * payloadHash defaults to the hash of an empty body
74
+ * @returns {string}
75
+ */
76
+ function presignUrl({ method = 'GET', url, headers = {}, region, service, expires, credentials, now = new Date(), payloadHash = sha256('') }) {
77
+ const { amzDate, date } = stamp(now)
78
+ const u = new URL(url)
79
+ const scope = `${date}/${region}/${service}/aws4_request`
80
+ const { text, signedHeaders } = canonicalHeaders({ host: u.host, ...headers })
81
+ const query = canonicalQuery([
82
+ ...u.searchParams.entries(),
83
+ ['X-Amz-Algorithm', 'AWS4-HMAC-SHA256'],
84
+ ['X-Amz-Credential', `${credentials.accessKeyId}/${scope}`],
85
+ ['X-Amz-Date', amzDate],
86
+ ['X-Amz-Expires', String(expires)],
87
+ ...(credentials.sessionToken ? [['X-Amz-Security-Token', credentials.sessionToken]] : []),
88
+ ['X-Amz-SignedHeaders', signedHeaders],
89
+ ])
90
+ const canonicalRequest = [method.toUpperCase(), u.pathname || '/', query, text, signedHeaders, payloadHash].join('\n')
91
+ const sig = signature({ canonicalRequest, amzDate, scope, date, region, service, secretAccessKey: credentials.secretAccessKey })
92
+ return `${u.origin}${u.pathname}?${query}&X-Amz-Signature=${sig}`
93
+ }
94
+
95
+ module.exports = { signRequest, presignUrl }
@@ -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 }
@@ -56,7 +56,7 @@ async function adminsCancel(positional, flags, deps = {}) {
56
56
  }
57
57
 
58
58
  /**
59
- * Accept an offer made to you (your own deployment login, verified email); repeat to resume an interrupted accept.
59
+ * Accept an offer made to you (your own deployment login, verified email or phone number); repeat to resume an interrupted accept.
60
60
  * @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps]
61
61
  */
62
62
  async function adminsAccept(positional, flags, deps = {}) {
@@ -64,7 +64,7 @@ async function adminsAccept(positional, flags, deps = {}) {
64
64
  return transferOf(await permissionsRequest('permissions access-admins accept', flags, deps, 'POST', '/me/access-admin-transfers/accept', { transferId }))
65
65
  }
66
66
 
67
- /** Record your own activation (your deployment login, verified email). @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
67
+ /** Record your own activation (your deployment login, verified email or phone number). @param {string[]} positional @param {AdminFlags} flags @param {Deps} [deps] */
68
68
  async function adminsActivate(positional, flags, deps = {}) {
69
69
  const body = await permissionsRequest('permissions access-admins activate', flags, deps, 'POST', '/me/activation', {})
70
70
  return body.data.attributes
@@ -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,65 @@
1
+ // `saaslayer admin allowlist list|add|remove <email>|open|close` — platform operators manage the control plane's signup
2
+ // allowlist (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
+ /**
46
+ * Sets enforcement: true lets only listed emails sign up, false lets anyone sign up. The emails are kept either way.
47
+ * @param {Record<string, any>} flags @param {boolean} enabled @returns {Promise<Allowlist>}
48
+ */
49
+ async function setEnforcement(flags, enabled) {
50
+ const list = allowlistOf(await jsonApiCall('PATCH', '/api/signup-allowlist', { enabled }, flags))
51
+ print(list)
52
+ return list
53
+ }
54
+
55
+ /** @param {Record<string, any>} flags @returns {Promise<Allowlist>} */
56
+ async function allowlistOpen(flags = {}) {
57
+ return setEnforcement(flags, false)
58
+ }
59
+
60
+ /** @param {Record<string, any>} flags @returns {Promise<Allowlist>} */
61
+ async function allowlistClose(flags = {}) {
62
+ return setEnforcement(flags, true)
63
+ }
64
+
65
+ module.exports = { allowlistList, allowlistAdd, allowlistRemove, allowlistOpen, allowlistClose }
@@ -0,0 +1,83 @@
1
+ // `saaslayer permissions api-keys create|list|get|revoke`: scoped API keys on a deployment's permissions /api-keys API, for
2
+ // deployments without a console (e.g. permissions-only with an external login provider). A key never exceeds its minter.
3
+ 'use strict'
4
+ const { exchangeIamToken } = require('../iam-session')
5
+ const { permissionsRequest } = require('../permissions-request')
6
+
7
+ /**
8
+ * @typedef {import('../permissions-request').PermissionsFlags & { user?: string, name?: string, allow?: string|string[],
9
+ * deny?: string|string[], scope?: string, 'expires-at'?: string }} KeyFlags
10
+ * @typedef {{ exchange?: typeof exchangeIamToken }} Deps
11
+ * @typedef {{ product?: string, service: string, resource: string, action: string }} Tuple
12
+ */
13
+
14
+ /** @param {string|string[]|undefined} v @returns {string[]} */
15
+ const listOf = (v) => (v === undefined ? [] : Array.isArray(v) ? v : [v])
16
+
17
+ /**
18
+ * One --allow/--deny value as a permission tuple: service:resource:action, or product:service:resource:action.
19
+ * @param {string} label @param {string} flag @param {string} value
20
+ * @returns {Tuple}
21
+ */
22
+ function tupleOf(label, flag, value) {
23
+ const parts = String(value).split(':')
24
+ if (parts.some((p) => !p) || (parts.length !== 3 && parts.length !== 4)) {
25
+ throw new Error(`${label}: --${flag} "${value}" must be service:resource:action (or product:service:resource:action)`)
26
+ }
27
+ const [product, service, resource, action] = parts.length === 4 ? parts : [undefined, ...parts]
28
+ return { ...(product ? { product } : {}), service, resource, action }
29
+ }
30
+
31
+ /** @param {string} label @param {string[]} positional */
32
+ function keyIdOf(label, positional) {
33
+ if (!positional[0]) throw new Error(`${label}: <keyId> is required`)
34
+ return positional[0]
35
+ }
36
+
37
+ /** @param {{ data: { id: string, attributes: Record<string, unknown> } }} body */
38
+ const keyOf = (body) => ({ id: body.data.id, ...body.data.attributes })
39
+
40
+ /**
41
+ * Mint a key for an owner (--user) holding exactly the --allow tuples (minus --deny), optionally limited to an org --scope and
42
+ * an --expires-at time. The result carries the key itself, shown this once.
43
+ * @param {string[]} positional @param {KeyFlags} flags @param {Deps} [deps]
44
+ */
45
+ async function apiKeysCreate(positional, flags, deps = {}) {
46
+ const label = 'permissions api-keys create'
47
+ if (!flags.user) throw new Error(`${label}: --user <owner id> is required`)
48
+ if (!flags.name) throw new Error(`${label}: --name <name> is required`)
49
+ const allows = listOf(flags.allow).map((v) => tupleOf(label, 'allow', v))
50
+ if (!allows.length) throw new Error(`${label}: at least one --allow service:resource:action is required (repeatable)`)
51
+ const denies = listOf(flags.deny).map((v) => tupleOf(label, 'deny', v))
52
+ const request = {
53
+ userId: flags.user,
54
+ name: flags.name,
55
+ permissions: { allows, denies },
56
+ ...(flags.scope ? { scope: flags.scope } : {}),
57
+ ...(flags['expires-at'] ? { expiresAt: flags['expires-at'] } : {}),
58
+ }
59
+ return keyOf(await permissionsRequest(label, flags, deps, 'POST', '/api-keys', request))
60
+ }
61
+
62
+ /** Keys the caller may see; --user narrows to one owner's. @param {string[]} positional @param {KeyFlags} flags @param {Deps} [deps] */
63
+ async function apiKeysList(positional, flags, deps = {}) {
64
+ const query = flags.user ? `?userId=${encodeURIComponent(flags.user)}` : ''
65
+ const body = await permissionsRequest('permissions api-keys list', flags, deps, 'GET', `/api-keys${query}`)
66
+ return (body.data || []).map((/** @type {{ id: string, attributes: object }} */ d) => ({ id: d.id, ...d.attributes }))
67
+ }
68
+
69
+ /** @param {string[]} positional @param {KeyFlags} flags @param {Deps} [deps] */
70
+ async function apiKeysGet(positional, flags, deps = {}) {
71
+ const label = 'permissions api-keys get'
72
+ return keyOf(await permissionsRequest(label, flags, deps, 'GET', `/api-keys/${encodeURIComponent(keyIdOf(label, positional))}`))
73
+ }
74
+
75
+ /** Revoke a key; it stops authenticating at once. @param {string[]} positional @param {KeyFlags} flags @param {Deps} [deps] */
76
+ async function apiKeysRevoke(positional, flags, deps = {}) {
77
+ const label = 'permissions api-keys revoke'
78
+ const id = keyIdOf(label, positional)
79
+ await permissionsRequest(label, flags, deps, 'DELETE', `/api-keys/${encodeURIComponent(id)}`)
80
+ return { id, revoked: true }
81
+ }
82
+
83
+ module.exports = { apiKeysCreate, apiKeysList, apiKeysGet, apiKeysRevoke }
@@ -0,0 +1,77 @@
1
+ // `saaslayer audit erase <suid> [--email E …]`: GDPR erasure of a person from a deployment's audit trail through its
2
+ // permissions API (POST /audit/identities/:personId/erase, scope audit:person:erase). Addresses are never printed.
3
+ 'use strict'
4
+ const { permissionsRequest } = require('../permissions-request')
5
+ const { discoverFromFlags } = require('../discovery')
6
+
7
+ const LABEL = 'audit erase'
8
+ /** The erase route's limits (permissions-service src/audit-erasure.js). */
9
+ const MAX_EMAILS = 50
10
+ const MAX_EMAIL_LENGTH = 254
11
+
12
+ /**
13
+ * @typedef {import('../permissions-request').PermissionsFlags & { email?: string|string[]|boolean, 'discovery-url'?: string }} EraseFlags
14
+ * @typedef {import('../permissions-request').Deps & { log?: (line: string) => void, discover?: import('../discovery').discoverDeployment }} Deps
15
+ */
16
+
17
+ /**
18
+ * The --email values, trimmed. Errors never echo an address.
19
+ * @param {EraseFlags['email']} value
20
+ * @returns {string[]}
21
+ */
22
+ function emailsOf(value) {
23
+ if (value === undefined) return []
24
+ const emails = [].concat(value).map((e) => (typeof e === 'string' ? e.trim() : ''))
25
+ if (emails.some((e) => !e)) throw new Error(`${LABEL}: --email needs an address`)
26
+ if (emails.length > MAX_EMAILS) throw new Error(`${LABEL}: at most ${MAX_EMAILS} --email addresses (got ${emails.length})`)
27
+ if (emails.some((e) => e.length > MAX_EMAIL_LENGTH)) throw new Error(`${LABEL}: each --email must be at most ${MAX_EMAIL_LENGTH} characters`)
28
+ return emails
29
+ }
30
+
31
+ /**
32
+ * The permissions API base: --api-base (or $SAASLAYER_API_BASE); an external ID token pins its own; else discovered from
33
+ * the deployment's public outputs (--deployment <dep_id|env> or --discovery-url).
34
+ * @param {EraseFlags} flags @param {Deps} deps
35
+ * @returns {Promise<string|undefined>}
36
+ */
37
+ async function apiBaseOf(flags, deps) {
38
+ const given = flags['api-base'] || process.env.SAASLAYER_API_BASE
39
+ if (given || flags['id-token-file'] || process.env.SAASLAYER_ID_TOKEN) return given
40
+ if (!flags.deployment && !flags['discovery-url']) throw new Error(`${LABEL}: --api-base, --deployment or --discovery-url is required`)
41
+ const { doc } = await discoverFromFlags(flags, { discover: deps.discover })
42
+ return doc.permissionsApiBase
43
+ }
44
+
45
+ /** What to do about a refusal, by status. */
46
+ const HINTS = /** @type {Record<number, string>} */ ({
47
+ 403: 'the caller needs the audit:person:erase scope at deployment scope (platform-only: an IAM principal or API key granted it, or the deployment\'s user-service onboarding key; org admins never have it)',
48
+ 503: 'the deployment has no audit table, so there is no audit trail to erase from',
49
+ })
50
+
51
+ /**
52
+ * Erase <suid> from the audit trail: names and emails come off every entry that names them (and invitation entries holding
53
+ * one of the --email addresses); ids and events stay. Prints and returns { personId, status, emails: <count> }. A
54
+ * `requested` status is finished by the deployment's audit recovery worker within minutes; running it again is safe.
55
+ * @param {string[]} positional @param {EraseFlags} flags @param {Deps} [deps]
56
+ */
57
+ async function auditErase(positional, flags, deps = {}) {
58
+ const log = deps.log || console.log
59
+ const personId = positional[0]
60
+ if (!personId) throw new Error(`${LABEL}: <suid> is required`)
61
+ const emails = emailsOf(flags.email)
62
+ const apiBase = await apiBaseOf(flags, deps)
63
+ /** @type {any} */
64
+ let body
65
+ try {
66
+ body = await permissionsRequest(LABEL, { ...flags, 'api-base': apiBase }, deps, 'POST', `/audit/identities/${encodeURIComponent(personId)}/erase`, emails.length ? { emails } : {})
67
+ } catch (err) {
68
+ const hint = HINTS[/** @type {{ status?: number }} */ (err).status || 0]
69
+ if (hint) err.message = `${err.message}\n ${hint}`
70
+ throw err
71
+ }
72
+ const out = { personId: body.data.id, status: body.data.attributes.status, emails: emails.length }
73
+ log(JSON.stringify(out, null, 2))
74
+ return out
75
+ }
76
+
77
+ module.exports = { auditErase, MAX_EMAILS, MAX_EMAIL_LENGTH }