saaslayer 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/saaslayer.js +23 -11
- package/package.json +7 -7
- package/src/cdn-aws.js +67 -0
- package/src/cdn-publication.js +146 -0
- package/src/cdn-publisher.js +166 -0
- package/src/commands/cdn.js +66 -0
- package/src/commands/deploy.js +4 -3
- package/src/commands/lifecycle.js +20 -2
- package/src/commands/operations.js +8 -3
- package/src/commands/stacks.js +2 -0
- package/src/commands/users-management.js +2 -2
- package/src/deployments.js +5 -2
- package/src/module-catalog.js +15 -5
- package/src/sms/scope.js +4 -2
- package/src/source-branch.js +36 -0
- package/src/users-import/ids.js +1 -1
- package/templates/saaslayer-foundation.yml +215 -281
- package/vendor/config/login-domain.js +213 -0
- package/vendor/discovery/index.d.mts +109 -0
- package/vendor/discovery/index.mjs +409 -0
- package/vendor/ids/index.d.ts +21 -0
- package/vendor/ids/index.js +237 -0
- package/vendor/migrations/backups.js +118 -0
- package/vendor/migrations/child.js +78 -0
- package/vendor/migrations/credentials.js +103 -0
- package/vendor/migrations/errors.js +30 -0
- package/vendor/migrations/exec-child.js +78 -0
- package/vendor/migrations/gate.js +51 -0
- package/vendor/migrations/index.js +30 -0
- package/vendor/migrations/inventory.js +92 -0
- package/vendor/migrations/log.js +14 -0
- package/vendor/migrations/release.js +45 -0
- package/vendor/migrations/report.js +129 -0
- package/vendor/migrations/rules.js +104 -0
- package/vendor/migrations/run.js +311 -0
- package/vendor/migrations/session-policy.js +37 -0
- package/vendor/migrations/step-guard.js +82 -0
- package/vendor/operations/activity.d.ts +21 -0
- package/vendor/operations/activity.js +126 -0
- package/vendor/operations/index.d.ts +72 -0
- package/vendor/operations/index.js +510 -0
- package/vendor/permissions-engine-core/account-status.js +270 -0
- package/vendor/permissions-engine-core/delegation.js +174 -0
- package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
- package/vendor/permissions-engine-core/sso-claims.js +206 -0
- package/vendor/user-management/cognito/emails/token-registry.js +48 -0
- package/vendor/user-management/email/validate.js +207 -0
- package/vendor/user-management/extensibility/hook-contract.js +720 -0
- package/vendor/user-management/extensibility/safe-webhook.js +85 -0
- package/vendor/user-management/identity/admission.js +215 -0
- package/vendor/user-management/identity/attr.js +27 -0
- package/vendor/user-management/identity/attribute-registry.js +115 -0
- package/vendor/user-management/identity/email.js +25 -0
- package/vendor/user-management/identity/ensure-suid.js +74 -0
- package/vendor/user-management/identity/pointers.js +192 -0
- package/vendor/user-management/identity/stitch-provider.js +275 -0
- package/vendor/user-management/management/apply-request.js +227 -0
- package/vendor/user-management/management/core-profile.js +110 -0
- package/vendor/user-management/management/index.js +23 -0
- package/vendor/user-management/management/purposes.js +94 -0
- package/vendor/user-management/management/registry.js +569 -0
- package/vendor/user-management/store/table.js +332 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// One local-management request applied to an instance's registry: owner bootstrap (resolving or inviting each owner's
|
|
2
|
+
// own-pool account at its suid), machine key lifecycle and human grants. Run by the deployer's seed and the owner's CLI.
|
|
3
|
+
'use strict'
|
|
4
|
+
|
|
5
|
+
const { assertPurposes } = require('./purposes')
|
|
6
|
+
const { managementError } = require('./registry')
|
|
7
|
+
const { MANAGEMENT_BOOTSTRAP } = require('./core-profile')
|
|
8
|
+
|
|
9
|
+
const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
|
10
|
+
const KEY_PHASES = Object.freeze(['introduce', 'activate', 'retire', 'revoke', 'status'])
|
|
11
|
+
const GRANT_PHASES = Object.freeze(['grant', 'revoke', 'status'])
|
|
12
|
+
/** Onboarding routes whose account's credentials its mailbox holder chose: an invitation registration, the first-admin bootstrap. */
|
|
13
|
+
const INVITED_VIA = new Set(['invitation', 'deployment-bootstrap'])
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {{ suid: string, email: string, purposes: string[] }} Owner
|
|
17
|
+
* @typedef {{ get: (email: string) => Promise<{ suid: string|null, sub: string|null }|null>, invite: (account: { email: string, suid: string }) => Promise<{ sub: string|null }> }} OwnerAccounts
|
|
18
|
+
* the instance's own pool: find the account holding an email; create one at a suid (Cognito mails the invitation)
|
|
19
|
+
* @typedef {ReturnType<typeof import('./core-profile').coreIdentity>} CoreIdentity
|
|
20
|
+
* the instance's core table: PROFILE projections, ONBOARDING markers and the owner invitation's claim
|
|
21
|
+
* @typedef {{ action: 'bootstrap', owners: unknown, reason?: string, recover?: boolean }
|
|
22
|
+
* | { action: 'key', phase: string, callerId?: string, purposes?: string[], keyId?: string, sha256?: string, reason?: string }
|
|
23
|
+
* | { action: 'grant', phase: string, principal?: string, email?: string, purposes?: string[], reason?: string }} ManagementRequest
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The declared root owners (ManagementOwners / MANAGEMENT_OWNERS, or a bootstrap request's owners): a JSON array (or an
|
|
28
|
+
* array) of { suid, email, purposes }, validated whole. Empty or absent declares none.
|
|
29
|
+
* @param {unknown} raw
|
|
30
|
+
* @returns {Owner[]}
|
|
31
|
+
*/
|
|
32
|
+
function parseOwners(raw) {
|
|
33
|
+
let list = raw
|
|
34
|
+
if (typeof raw === 'string') {
|
|
35
|
+
if (!raw.trim()) return []
|
|
36
|
+
try {
|
|
37
|
+
list = JSON.parse(raw)
|
|
38
|
+
} catch {
|
|
39
|
+
throw managementError('MANAGEMENT_INVALID', 'ManagementOwners is not valid JSON')
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (list === undefined || list === null) return []
|
|
43
|
+
if (!Array.isArray(list)) throw managementError('MANAGEMENT_INVALID', 'ManagementOwners must be an array of { suid, email, purposes }')
|
|
44
|
+
const seen = new Set()
|
|
45
|
+
return list.map((entry, i) => {
|
|
46
|
+
const at = `ManagementOwners[${i}]`
|
|
47
|
+
const suid = typeof entry?.suid === 'string' ? entry.suid.trim() : ''
|
|
48
|
+
const email = typeof entry?.email === 'string' ? entry.email.trim().toLowerCase() : ''
|
|
49
|
+
if (!suid || suid.length > 256 || suid.includes('#')) throw managementError('MANAGEMENT_INVALID', `${at} needs the owner's suid`)
|
|
50
|
+
if (!EMAIL_SHAPE.test(email)) throw managementError('MANAGEMENT_INVALID', `${at} needs the owner's email`)
|
|
51
|
+
let purposes
|
|
52
|
+
try {
|
|
53
|
+
purposes = assertPurposes(entry.purposes, 'human')
|
|
54
|
+
} catch (err) {
|
|
55
|
+
throw managementError('MANAGEMENT_INVALID', `${at}: ${/** @type {Error} */ (err).message}`)
|
|
56
|
+
}
|
|
57
|
+
if (seen.has(suid) || seen.has(email)) throw managementError('MANAGEMENT_INVALID', `${at} names an owner (suid or email) already declared`)
|
|
58
|
+
seen.add(suid)
|
|
59
|
+
seen.add(email)
|
|
60
|
+
return { suid, email, purposes }
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Whether the account at a suid was made by an invitation flow, so its credentials are its mailbox holder's: an owner
|
|
66
|
+
* invitation for this email, an invitation registration or the first-admin bootstrap (the suid's ONBOARDING marker).
|
|
67
|
+
* An account an import or a set password made, an adopted one, or one with no marker is not.
|
|
68
|
+
* @param {Record<string, any>|null} marker @param {string} email the account's email
|
|
69
|
+
*/
|
|
70
|
+
function madeByInvitation(marker, email) {
|
|
71
|
+
if (!marker) return false
|
|
72
|
+
if (marker.via === MANAGEMENT_BOOTSTRAP) return marker.email === email
|
|
73
|
+
return INVITED_VIA.has(marker.via)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** @param {Record<string, any>|null} marker @param {string} suid */
|
|
77
|
+
const untrustedAccount = (marker, suid) => managementError('MANAGEMENT_ACCOUNT_UNTRUSTED',
|
|
78
|
+
`the account at ${suid} was not made by an invitation (${marker ? marker.via : 'no onboarding record'}), so its credentials may not be its mailbox holder's; `
|
|
79
|
+
+ 'no management grant is bound to it. Delete that account, then bootstrap or grant again so its owner is invited')
|
|
80
|
+
|
|
81
|
+
/** @param {CoreIdentity|undefined} identity @param {string} needs */
|
|
82
|
+
function requireIdentity(identity, needs) {
|
|
83
|
+
if (!identity) throw managementError('MANAGEMENT_UNAVAILABLE', `${needs} needs the instance's core table (CoreTableName)`)
|
|
84
|
+
return identity
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Each owner's own-pool account, at its exact suid. Checked for every owner before anything is written: an account
|
|
89
|
+
* holding the email under another suid is a conflict; an existing account is bound only when its registry grant already
|
|
90
|
+
* names it or an invitation made it (else MANAGEMENT_ACCOUNT_UNTRUSTED, recovery included). A missing account is
|
|
91
|
+
* invited at that suid after the invitation claims the suid's onboarding marker (a suid another onboarding holds is a
|
|
92
|
+
* conflict, before Cognito is asked); the invited account's sub is recorded on the marker. Each outcome carries the sub
|
|
93
|
+
* the owner's grant is bound to.
|
|
94
|
+
* @param {OwnerAccounts} accounts @param {CoreIdentity} identity
|
|
95
|
+
* @param {ReturnType<typeof import('./registry').createManagementRegistry>} registry @param {Owner[]} owners
|
|
96
|
+
* @returns {Promise<Array<{ suid: string, sub: string|null, account: 'existing'|'invited' }>>}
|
|
97
|
+
*/
|
|
98
|
+
async function resolveOwnerAccounts(accounts, identity, registry, owners) {
|
|
99
|
+
const found = []
|
|
100
|
+
for (const owner of owners) {
|
|
101
|
+
const account = await accounts.get(owner.email)
|
|
102
|
+
if (account && account.suid !== owner.suid) throw managementError('MANAGEMENT_CONFLICT', `the account for owner ${owner.suid}'s email carries another suid; bootstrap never remaps an identity`)
|
|
103
|
+
const marker = account ? await identity.onboarding(owner.suid) : null
|
|
104
|
+
if (account) {
|
|
105
|
+
const bound = await registry.readCaller('human', owner.suid)
|
|
106
|
+
const alreadyBound = Boolean(bound && bound.principalSub && bound.principalSub === account.sub)
|
|
107
|
+
if (!alreadyBound && !madeByInvitation(marker, owner.email)) throw untrustedAccount(marker, owner.suid)
|
|
108
|
+
if (marker && marker.via === MANAGEMENT_BOOTSTRAP && marker.sub && marker.sub !== account.sub) {
|
|
109
|
+
throw managementError('MANAGEMENT_CONFLICT', `owner ${owner.suid}'s account is not the one its invitation made`)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
found.push({ owner, account, marker })
|
|
113
|
+
}
|
|
114
|
+
const outcomes = []
|
|
115
|
+
for (const { owner, account, marker } of found) {
|
|
116
|
+
let sub
|
|
117
|
+
if (account) {
|
|
118
|
+
sub = account.sub
|
|
119
|
+
// An invitation that stopped before recording its account: record it now.
|
|
120
|
+
if (marker && marker.via === MANAGEMENT_BOOTSTRAP && !marker.sub && sub) await identity.recordBootstrapInvite({ suid: owner.suid, email: owner.email, sub })
|
|
121
|
+
} else {
|
|
122
|
+
await identity.claimBootstrapInvite({ suid: owner.suid, email: owner.email })
|
|
123
|
+
sub = (await accounts.invite({ email: owner.email, suid: owner.suid })).sub
|
|
124
|
+
if (sub) await identity.recordBootstrapInvite({ suid: owner.suid, email: owner.email, sub })
|
|
125
|
+
}
|
|
126
|
+
outcomes.push({ suid: owner.suid, sub, account: /** @type {'existing'|'invited'} */ (account ? 'existing' : 'invited') })
|
|
127
|
+
}
|
|
128
|
+
return outcomes
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The sub of the own-pool account a grantee's suid names. An owner invitation's account is found by the email and sub
|
|
133
|
+
* its marker recorded (never the PROFILE, which another account's projection can rewrite); otherwise by the email the
|
|
134
|
+
* PROFILE projects, whose account must be the one projected (same sub). The account must carry the suid. Re-binding an
|
|
135
|
+
* existing grant to another account needs that account to be made by an invitation. None is not found; a mismatch is a
|
|
136
|
+
* conflict (nothing is granted).
|
|
137
|
+
* @param {OwnerAccounts} accounts @param {CoreIdentity|undefined} identity
|
|
138
|
+
* @param {ReturnType<typeof import('./registry').createManagementRegistry>} registry @param {string} suid
|
|
139
|
+
* @returns {Promise<string>}
|
|
140
|
+
*/
|
|
141
|
+
async function granteeSub(accounts, identity, registry, suid) {
|
|
142
|
+
const core = requireIdentity(identity, 'granting')
|
|
143
|
+
const marker = await core.onboarding(suid)
|
|
144
|
+
let account = null
|
|
145
|
+
let email = null
|
|
146
|
+
if (marker && marker.via === MANAGEMENT_BOOTSTRAP) {
|
|
147
|
+
email = marker.email || null
|
|
148
|
+
account = email ? await accounts.get(email) : null
|
|
149
|
+
if (account && marker.sub && account.sub !== marker.sub) throw managementError('MANAGEMENT_CONFLICT', `the account at ${suid}'s invited email is not the one its invitation made; a grant is never bound to it`)
|
|
150
|
+
} else {
|
|
151
|
+
const profile = await core.profile(suid)
|
|
152
|
+
email = profile && profile.email
|
|
153
|
+
account = email ? await accounts.get(email) : null
|
|
154
|
+
if (account && profile && profile.sub && account.sub !== profile.sub) throw managementError('MANAGEMENT_CONFLICT', `the account ${suid}'s profile names is not the account it projected; a grant is never bound to it`)
|
|
155
|
+
}
|
|
156
|
+
if (!account) throw managementError('MANAGEMENT_NOT_FOUND', `no own-pool account holds ${suid}; the grantee signs in (or is created) first`)
|
|
157
|
+
if (account.suid !== suid || !account.sub) throw managementError('MANAGEMENT_CONFLICT', `the account ${suid}'s profile names carries another suid; a grant is never bound to it`)
|
|
158
|
+
const current = await registry.readCaller('human', suid)
|
|
159
|
+
if (current && current.principalSub && current.principalSub !== account.sub && !madeByInvitation(marker, /** @type {string} */ (email))) throw untrustedAccount(marker, suid)
|
|
160
|
+
return account.sub
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A registry status as reported (seed results, operation components, CLI output): no emails, and each caller's key ids
|
|
165
|
+
* and states as `keys` (operation views redact any field named like a credential).
|
|
166
|
+
* @param {Record<string, any>} status
|
|
167
|
+
*/
|
|
168
|
+
function reportStatus(status) {
|
|
169
|
+
return { ...status, callers: status.callers.map(({ email, credentials, ...caller }) => ({ ...caller, keys: credentials })) }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Apply one request. Errors carry the registry's codes (MANAGEMENT_INVALID, _REASON_REQUIRED, _BUSY, _CONFLICT, _GATE,
|
|
174
|
+
* _NOT_FOUND, _UNAVAILABLE) and MANAGEMENT_ACCOUNT_UNTRUSTED. material is the owner's durable store for a standalone key
|
|
175
|
+
* issuance (raw value returned).
|
|
176
|
+
* @param {{ registry: ReturnType<typeof import('./registry').createManagementRegistry>, accounts: OwnerAccounts,
|
|
177
|
+
* identity?: CoreIdentity, request: ManagementRequest, actor: unknown, material?: import('./registry').MaterialStore }} input
|
|
178
|
+
* identity: the core table, how a bootstrap claims and a grant finds its grantee's account (required for both)
|
|
179
|
+
* @returns {Promise<Record<string, any>>}
|
|
180
|
+
*/
|
|
181
|
+
async function applyManagementRequest({ registry, accounts, identity, request, actor, material }) {
|
|
182
|
+
const action = request && request.action
|
|
183
|
+
if (action === 'bootstrap') {
|
|
184
|
+
const r = /** @type {{ owners: unknown, reason?: string, recover?: boolean }} */ (request)
|
|
185
|
+
const owners = parseOwners(r.owners)
|
|
186
|
+
if (owners.length === 0) throw managementError('MANAGEMENT_INVALID', 'bootstrap names at least one owner')
|
|
187
|
+
const accountOutcomes = await resolveOwnerAccounts(accounts, requireIdentity(identity, 'bootstrap'), registry, owners)
|
|
188
|
+
const bound = owners.map((o, i) => ({ ...o, sub: accountOutcomes[i].sub }))
|
|
189
|
+
const result = await registry.bootstrap({ owners: bound, actor, ...(r.reason ? { reason: r.reason } : {}), ...(r.recover ? { recover: true } : {}) })
|
|
190
|
+
return { action, owners: result.owners.map((o, i) => ({ suid: o.suid, account: accountOutcomes[i].account, outcome: o.outcome })) }
|
|
191
|
+
}
|
|
192
|
+
if (action === 'key') {
|
|
193
|
+
const r = /** @type {{ phase: string, callerId?: string, purposes?: string[], keyId?: string, sha256?: string, reason?: string }} */ (request)
|
|
194
|
+
if (!KEY_PHASES.includes(r.phase)) throw managementError('MANAGEMENT_INVALID', `phase must be one of ${KEY_PHASES.join(', ')}`)
|
|
195
|
+
if (r.phase === 'status') return { action, phase: r.phase, ...reportStatus(await registry.status()) }
|
|
196
|
+
const callerId = /** @type {string} */ (r.callerId)
|
|
197
|
+
if (r.phase === 'introduce') {
|
|
198
|
+
if (r.sha256) {
|
|
199
|
+
const out = await registry.introduceKey({ callerId, purposes: /** @type {string[]} */ (r.purposes), actor, keyId: r.keyId, sha256: r.sha256 })
|
|
200
|
+
return { action, phase: r.phase, callerId: out.callerId, keyId: out.keyId }
|
|
201
|
+
}
|
|
202
|
+
if (!material) throw managementError('MANAGEMENT_INVALID', 'a key is introduced by its digest (managed) or with the owner\'s material store (standalone)')
|
|
203
|
+
const out = await registry.issueKey({ callerId, purposes: /** @type {string[]} */ (r.purposes), actor, material })
|
|
204
|
+
return { action, phase: r.phase, callerId: out.callerId, keyId: out.keyId, key: out.key, reused: out.reused }
|
|
205
|
+
}
|
|
206
|
+
if (!r.keyId) throw managementError('MANAGEMENT_INVALID', `${r.phase} names the key (--key-id)`)
|
|
207
|
+
const transition = { callerId, keyId: r.keyId, actor, ...(material ? { material } : {}) }
|
|
208
|
+
const out = r.phase === 'activate'
|
|
209
|
+
? await registry.activateKey(transition)
|
|
210
|
+
: r.phase === 'retire'
|
|
211
|
+
? await registry.retireKey(transition)
|
|
212
|
+
: await registry.revokeKey({ ...transition, reason: r.reason })
|
|
213
|
+
return { action, phase: r.phase, ...out }
|
|
214
|
+
}
|
|
215
|
+
if (action === 'grant') {
|
|
216
|
+
const r = /** @type {{ phase: string, principal?: string, email?: string, purposes?: string[], reason?: string }} */ (request)
|
|
217
|
+
if (!GRANT_PHASES.includes(r.phase)) throw managementError('MANAGEMENT_INVALID', `phase must be one of ${GRANT_PHASES.join(', ')}`)
|
|
218
|
+
if (r.phase === 'status') return { action, phase: r.phase, ...reportStatus(await registry.status()) }
|
|
219
|
+
const out = r.phase === 'grant'
|
|
220
|
+
? await registry.grant({ principal: /** @type {string} */ (r.principal), sub: await granteeSub(accounts, identity, registry, /** @type {string} */ (r.principal)), purposes: /** @type {string[]} */ (r.purposes), actor, ...(r.email ? { email: r.email } : {}), ...(r.reason ? { reason: r.reason } : {}) })
|
|
221
|
+
: await registry.revokeGrant({ principal: /** @type {string} */ (r.principal), reason: r.reason, actor })
|
|
222
|
+
return { action, phase: r.phase, ...out }
|
|
223
|
+
}
|
|
224
|
+
throw managementError('MANAGEMENT_INVALID', 'action must be bootstrap, key or grant')
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
module.exports = { parseOwners, resolveOwnerAccounts, applyManagementRequest, reportStatus }
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// The core-table identity records local management needs: a suid's PROFILE projection and its ONBOARDING marker (read
|
|
2
|
+
// strongly consistent), and the owner invitation's create-only claim of that marker. Shared by the seed and the owner's CLI.
|
|
3
|
+
'use strict'
|
|
4
|
+
|
|
5
|
+
const { GetCommand, PutCommand } = require('@aws-sdk/lib-dynamodb')
|
|
6
|
+
const { createAdmissions } = require('../identity/admission')
|
|
7
|
+
const { managementError } = require('./registry')
|
|
8
|
+
|
|
9
|
+
/** The ONBOARDING via an owner invitation claims (registration/identity's ONBOARDING_VIA.MANAGEMENT_BOOTSTRAP, pinned by a test). */
|
|
10
|
+
const MANAGEMENT_BOOTSTRAP = 'management-bootstrap'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The core table key of a suid's PROFILE projection (the store's keys.userProfile, which a test pins this to).
|
|
14
|
+
* @param {string} suid
|
|
15
|
+
*/
|
|
16
|
+
const profileKey = (suid) => ({ pk: `USER#${suid}`, sk: 'PROFILE' })
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The core table key of a suid's ONBOARDING marker (the store's keys.userOnboarding, which a test pins this to).
|
|
20
|
+
* @param {string} suid
|
|
21
|
+
*/
|
|
22
|
+
const onboardingKey = (suid) => ({ pk: `USER#${suid}`, sk: 'ONBOARDING' })
|
|
23
|
+
|
|
24
|
+
/** @param {unknown} err */
|
|
25
|
+
const isConditionFailure = (err) => Boolean(err && /** @type {{ name?: string }} */ (err).name === 'ConditionalCheckFailedException')
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {{ doc: { send: (cmd: unknown) => Promise<any> }, tableName: string, now?: () => number }} deps the core table
|
|
29
|
+
* (CoreTableName); now = unix seconds
|
|
30
|
+
*/
|
|
31
|
+
function coreIdentity({ doc, tableName, now = () => Math.floor(Date.now() / 1000) }) {
|
|
32
|
+
/** @param {{ pk: string, sk: string }} key @returns {Promise<Record<string, any>|null>} */
|
|
33
|
+
const read = async (key) => {
|
|
34
|
+
const res = await doc.send(new GetCommand({ TableName: tableName, Key: key, ConsistentRead: true }))
|
|
35
|
+
return (res && res.Item) || null
|
|
36
|
+
}
|
|
37
|
+
/** @param {unknown} suid */
|
|
38
|
+
const valid = (suid) => Boolean(suid) && !String(suid).includes('#')
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
/**
|
|
42
|
+
* The email and Cognito sub a suid's PROFILE projects, or null without one.
|
|
43
|
+
* @param {string} suid
|
|
44
|
+
* @returns {Promise<{ email: string|null, sub: string|null }|null>}
|
|
45
|
+
*/
|
|
46
|
+
async profile(suid) {
|
|
47
|
+
if (!valid(suid)) return null
|
|
48
|
+
const item = await read(profileKey(suid))
|
|
49
|
+
if (!item) return null
|
|
50
|
+
return { email: typeof item.email === 'string' && item.email ? item.email : null, sub: typeof item.sub === 'string' && item.sub ? item.sub : null }
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How the suid was onboarded (its marker), or null.
|
|
55
|
+
* @param {string} suid
|
|
56
|
+
* @returns {Promise<Record<string, any>|null>}
|
|
57
|
+
*/
|
|
58
|
+
async onboarding(suid) {
|
|
59
|
+
return valid(suid) ? read(onboardingKey(suid)) : null
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Claim the suid for an owner invitation before Cognito is asked: the marker is created once, and only the same
|
|
64
|
+
* owner's invitation resumes it. Any other onboarding at the suid (an import, an invitation registration, another
|
|
65
|
+
* owner) holds it: MANAGEMENT_CONFLICT, nothing written.
|
|
66
|
+
* @param {{ suid: string, email: string }} owner
|
|
67
|
+
*/
|
|
68
|
+
async claimBootstrapInvite({ suid, email }) {
|
|
69
|
+
try {
|
|
70
|
+
await doc.send(new PutCommand({
|
|
71
|
+
TableName: tableName,
|
|
72
|
+
Item: { ...onboardingKey(suid), itemType: 'ONBOARDING', suid, via: MANAGEMENT_BOOTSTRAP, email, at: now() },
|
|
73
|
+
ConditionExpression: 'attribute_not_exists(pk)',
|
|
74
|
+
}))
|
|
75
|
+
} catch (err) {
|
|
76
|
+
if (!isConditionFailure(err)) throw err
|
|
77
|
+
const held = await read(onboardingKey(suid))
|
|
78
|
+
if (held && held.via === MANAGEMENT_BOOTSTRAP && held.email === email) return
|
|
79
|
+
throw managementError('MANAGEMENT_CONFLICT', `${suid} is already held by another onboarding (${held ? held.via : 'unknown'}); an owner is invited only at a suid no account holds`)
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Record the invited account's Cognito sub on the owner invitation's own marker (never on another onboarding's),
|
|
85
|
+
* and mark the account's admission pending.
|
|
86
|
+
* @param {{ suid: string, email: string, sub: string }} invited
|
|
87
|
+
*/
|
|
88
|
+
async recordBootstrapInvite({ suid, email, sub }) {
|
|
89
|
+
const held = await read(onboardingKey(suid))
|
|
90
|
+
if (!held || held.via !== MANAGEMENT_BOOTSTRAP || held.email !== email) {
|
|
91
|
+
throw managementError('MANAGEMENT_CONFLICT', `${suid}'s onboarding is not this owner's invitation; its account is not recorded`)
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
await doc.send(new PutCommand({
|
|
95
|
+
TableName: tableName,
|
|
96
|
+
Item: { ...held, sub },
|
|
97
|
+
ConditionExpression: 'via = :via AND email = :email',
|
|
98
|
+
ExpressionAttributeValues: { ':via': MANAGEMENT_BOOTSTRAP, ':email': email },
|
|
99
|
+
}))
|
|
100
|
+
} catch (err) {
|
|
101
|
+
if (!isConditionFailure(err)) throw err
|
|
102
|
+
throw managementError('MANAGEMENT_CONFLICT', `${suid}'s onboarding changed while its account was recorded`)
|
|
103
|
+
}
|
|
104
|
+
// The invited account exists: its admission is pending until its first sign-in settles its onboarding.
|
|
105
|
+
await createAdmissions({ doc, tableName, now: () => new Date(now() * 1000).toISOString() }).markPending({ suid, via: MANAGEMENT_BOOTSTRAP })
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
module.exports = { coreIdentity, profileKey, onboardingKey, MANAGEMENT_BOOTSTRAP }
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Opt-in local management of one user-service instance: the registry, its fixed purposes and the one request flow the
|
|
2
|
+
// deployer's seed and the owner's CLI share (vendored into the saaslayer CLI as vendor/user-management).
|
|
3
|
+
'use strict'
|
|
4
|
+
|
|
5
|
+
const registry = require('./registry')
|
|
6
|
+
const purposes = require('./purposes')
|
|
7
|
+
const applyRequest = require('./apply-request')
|
|
8
|
+
const coreProfile = require('./core-profile')
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The owner-only SSM path prefix of an instance's pending key material (standalone issuance): one create-only
|
|
12
|
+
* SecureString per key id under it. The default instance's segment is '_'.
|
|
13
|
+
* @param {string} deploymentId
|
|
14
|
+
* @param {string} serviceRef user-service or user-service@<instance>
|
|
15
|
+
*/
|
|
16
|
+
function managementMaterialPath(deploymentId, serviceRef) {
|
|
17
|
+
registry.managementPK(serviceRef)
|
|
18
|
+
if (!deploymentId || String(deploymentId).includes('/')) throw new Error('managementMaterialPath: a deployment id is required')
|
|
19
|
+
const instance = serviceRef.includes('@') ? serviceRef.split('@')[1] : '_'
|
|
20
|
+
return `/saaslayer/deployment/${deploymentId}/${instance}/users/management-material`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = { ...registry, ...purposes, ...applyRequest, ...coreProfile, managementMaterialPath }
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// The fixed purposes a local management caller holds (plan §4.3a) and what each opens: exact operation tuples, plus the
|
|
2
|
+
// input and caller-type limits a request is checked against. No purpose asserts actors or opens a route, and only a verified
|
|
3
|
+
// human's verifier-keys purpose mints a credential (a read-only customer verifier key): no machine key ever does.
|
|
4
|
+
'use strict'
|
|
5
|
+
|
|
6
|
+
const T = (/** @type {string} */ resource, /** @type {string} */ action) => `saaslayer:users:${resource}:${action}`
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The operation tuples each purpose opens. Nothing else, and no purpose is a prefix.
|
|
10
|
+
* @type {Readonly<Record<string, readonly string[]>>}
|
|
11
|
+
*/
|
|
12
|
+
const PURPOSE_OPERATIONS = Object.freeze({
|
|
13
|
+
'account-read': Object.freeze([T('account', 'read'), T('account', 'list'), T('operation', 'read')]),
|
|
14
|
+
'account-provisioning': Object.freeze([T('account', 'create'), T('operation', 'read')]),
|
|
15
|
+
'account-import': Object.freeze([T('account', 'create'), T('account', 'update-reserved'), T('operation', 'read')]),
|
|
16
|
+
'account-administration': Object.freeze([
|
|
17
|
+
T('account', 'read'), T('account', 'list'), T('account', 'create'), T('account', 'update'), T('account', 'disable'),
|
|
18
|
+
T('account', 'enable'), T('account', 'reset-password'), T('operation', 'read'),
|
|
19
|
+
]),
|
|
20
|
+
'account-deletion': Object.freeze([T('account', 'delete')]),
|
|
21
|
+
'account-sensitive': Object.freeze([T('account', 'update-reserved'), T('account', 'set-password'), T('account', 'adopt')]),
|
|
22
|
+
'account-recovery': Object.freeze([T('account', 'reset-mfa')]),
|
|
23
|
+
// The reconciliation sweep, and the SSO group-state replay (re-deliver every person's groups to permissions).
|
|
24
|
+
reconciliation: Object.freeze([T('reconciliation', 'read'), T('reconciliation', 'start'), T('sso-group-replay', 'start')]),
|
|
25
|
+
config: Object.freeze([T('config', 'read'), T('config', 'update')]),
|
|
26
|
+
'email-authoring': Object.freeze([T('email-template', 'read'), T('email-template', 'update'), T('email-template', 'publish'), T('email-template', 'test-send')]),
|
|
27
|
+
// The deployment owner's customer verifier keys (src/sso/verifier-keys.js): create (the key's one reveal), list, revoke.
|
|
28
|
+
'verifier-keys': Object.freeze([T('verifier-key', 'create'), T('verifier-key', 'read'), T('verifier-key', 'revoke')]),
|
|
29
|
+
// Every tenant's SSO connections (src/sso/management-access.js): the deployment owner's authority, held by the customer
|
|
30
|
+
// backend's server key (combo B) or a local human. Never sent to a browser: tenant pages use scoped management sessions.
|
|
31
|
+
'sso-management': Object.freeze([T('sso-connection', 'read'), T('sso-connection', 'manage'), T('sso-setup-link', 'issue'), T('sso-audit', 'read')]),
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
/** @type {readonly string[]} */
|
|
35
|
+
const PURPOSES = Object.freeze(Object.keys(PURPOSE_OPERATIONS))
|
|
36
|
+
|
|
37
|
+
/** Purposes only a verified local human may hold (a machine key is never issued them). */
|
|
38
|
+
const HUMAN_ONLY_PURPOSES = Object.freeze(['account-recovery', 'verifier-keys'])
|
|
39
|
+
|
|
40
|
+
/** Tuples no machine caller performs, whatever its purposes: MFA reset, test-send (decision 5) and verifier keys. */
|
|
41
|
+
const HUMAN_ONLY_TUPLES = Object.freeze([T('account', 'reset-mfa'), T('email-template', 'test-send'), T('verifier-key', 'create'), T('verifier-key', 'read'), T('verifier-key', 'revoke')])
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @param {string} message
|
|
45
|
+
* @returns {Error & { code: string, statusCode: number }}
|
|
46
|
+
*/
|
|
47
|
+
function invalid(message) {
|
|
48
|
+
return Object.assign(new Error(message), { code: 'MANAGEMENT_INVALID', statusCode: 422 })
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The purposes a grant or key may carry: known values, deduplicated in order, at least one, and none human-only for a
|
|
53
|
+
* machine. Throws MANAGEMENT_INVALID otherwise.
|
|
54
|
+
* @param {unknown} purposes
|
|
55
|
+
* @param {'human'|'machine'} callerType
|
|
56
|
+
* @returns {string[]}
|
|
57
|
+
*/
|
|
58
|
+
function assertPurposes(purposes, callerType) {
|
|
59
|
+
const list = Array.isArray(purposes) ? purposes : []
|
|
60
|
+
if (list.length === 0) throw invalid('name at least one purpose')
|
|
61
|
+
const unknown = list.filter((p) => typeof p !== 'string' || !PURPOSES.includes(p))
|
|
62
|
+
if (unknown.length) throw invalid(`unknown purpose ${unknown.map(String).join(', ')} (one of ${PURPOSES.join(', ')})`)
|
|
63
|
+
const unique = [...new Set(/** @type {string[]} */ (list))]
|
|
64
|
+
if (callerType === 'machine') {
|
|
65
|
+
const humanOnly = unique.filter((p) => HUMAN_ONLY_PURPOSES.includes(p))
|
|
66
|
+
if (humanOnly.length) throw invalid(`${humanOnly.join(', ')} is held by a verified local human only, never a machine key`)
|
|
67
|
+
}
|
|
68
|
+
return unique
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param {{ product: string, service: string, resource: string, action: string }} op */
|
|
72
|
+
const tupleOf = (op) => `${op.product}:${op.service}:${op.resource}:${op.action}`
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* May a management caller with these purposes perform every operation of this request? Checks tuple membership, the
|
|
76
|
+
* human-only tuples, and account-import's reserved-ID-create-only limit.
|
|
77
|
+
* @param {{ callerType: 'human'|'machine', purposes: readonly string[], operations: Array<{ product: string, service: string, resource: string, action: string }>|null }} input
|
|
78
|
+
* @returns {{ allowed: true } | { allowed: false, detail: string }}
|
|
79
|
+
*/
|
|
80
|
+
function managementAllows({ callerType, purposes, operations }) {
|
|
81
|
+
if (!operations || operations.length === 0) return { allowed: false, detail: 'no operation on this route is open to local management' }
|
|
82
|
+
const held = purposes.filter((p) => Object.prototype.hasOwnProperty.call(PURPOSE_OPERATIONS, p))
|
|
83
|
+
const tuples = operations.map(tupleOf)
|
|
84
|
+
const opens = (/** @type {string} */ purpose, /** @type {string} */ tuple) => PURPOSE_OPERATIONS[purpose].includes(tuple)
|
|
85
|
+
for (const tuple of tuples) {
|
|
86
|
+
if (callerType !== 'human' && HUMAN_ONLY_TUPLES.includes(tuple)) return { allowed: false, detail: `${tuple} is never performed by a machine management key` }
|
|
87
|
+
// account-import's reserved field is the caller-supplied suid of a create, never a reserved-attribute PATCH.
|
|
88
|
+
const allowedBy = held.filter((p) => opens(p, tuple) && !(p === 'account-import' && tuple === T('account', 'update-reserved') && !tuples.includes(T('account', 'create'))))
|
|
89
|
+
if (allowedBy.length === 0) return { allowed: false, detail: `the caller's purposes (${held.join(', ') || 'none'}) do not open ${tuple}` }
|
|
90
|
+
}
|
|
91
|
+
return { allowed: true }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = { PURPOSES, PURPOSE_OPERATIONS, HUMAN_ONLY_PURPOSES, assertPurposes, managementAllows }
|