saaslayer 0.3.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 (60) hide show
  1. package/README.md +105 -16
  2. package/bin/saaslayer.js +321 -60
  3. package/package.json +3 -2
  4. package/src/aws-sigv4.js +74 -26
  5. package/src/commands/access-admins.js +2 -2
  6. package/src/commands/admin-allowlist.js +23 -3
  7. package/src/commands/api-keys.js +83 -0
  8. package/src/commands/audit.js +77 -0
  9. package/src/commands/aws.js +355 -82
  10. package/src/commands/binding-handoff.js +174 -0
  11. package/src/commands/bindings.js +111 -0
  12. package/src/commands/catalog.js +30 -3
  13. package/src/commands/deploy.js +33 -10
  14. package/src/commands/env-export.js +58 -0
  15. package/src/commands/first-admin.js +15 -4
  16. package/src/commands/foundation.js +75 -117
  17. package/src/commands/hooks.js +271 -0
  18. package/src/commands/integration-credentials.js +1 -1
  19. package/src/commands/lifecycle.js +149 -24
  20. package/src/commands/login-domain.js +259 -0
  21. package/src/commands/permission-orgs.js +80 -0
  22. package/src/commands/release-manifest.js +17 -8
  23. package/src/commands/service-principals.js +42 -5
  24. package/src/commands/settings.js +21 -5
  25. package/src/commands/sms-registration.js +182 -0
  26. package/src/commands/sms.js +178 -0
  27. package/src/commands/social.js +265 -0
  28. package/src/commands/support-staff.js +72 -0
  29. package/src/commands/users-management.js +2 -20
  30. package/src/commands/users.js +56 -11
  31. package/src/commands/versions.js +61 -0
  32. package/src/connection-proof.js +41 -0
  33. package/src/deployments.js +1 -1
  34. package/src/foundation-change-set.js +180 -0
  35. package/src/foundation-home.js +121 -0
  36. package/src/foundation-template.js +51 -10
  37. package/src/foundation-trust-write.js +379 -0
  38. package/src/iam-session.js +14 -8
  39. package/src/login-domain.js +139 -0
  40. package/src/login-methods.js +118 -0
  41. package/src/module-catalog.js +3 -2
  42. package/src/release-manifest.js +11 -4
  43. package/src/scope.js +3 -1
  44. package/src/settings.js +85 -13
  45. package/src/sms/number.js +37 -0
  46. package/src/sms/registration-fields.js +167 -0
  47. package/src/sms/registration-validate.js +151 -0
  48. package/src/sms/registration.js +216 -0
  49. package/src/sms/release.js +55 -0
  50. package/src/sms/scope.js +86 -0
  51. package/src/sms/status.js +181 -0
  52. package/src/ssm-api.js +31 -0
  53. package/src/trust-entries.js +350 -0
  54. package/src/user-service-instance.js +27 -0
  55. package/src/users-api.js +55 -8
  56. package/src/users-import/checkpoint.js +76 -0
  57. package/src/users-import/import.js +233 -24
  58. package/src/versions.js +80 -0
  59. package/templates/saaslayer-foundation-region.yml +45 -1
  60. package/templates/saaslayer-foundation.yml +747 -296
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "saaslayer",
3
- "version": "0.3.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 && 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",
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/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 }
@@ -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
@@ -1,5 +1,5 @@
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.
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
3
  'use strict'
4
4
  const { jsonApiCall } = require('../api-client')
5
5
 
@@ -42,4 +42,24 @@ async function allowlistRemove(flags = {}, email) {
42
42
  return list
43
43
  }
44
44
 
45
- module.exports = { allowlistList, allowlistAdd, allowlistRemove }
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 }