saaslayer 0.4.1 → 0.4.3
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 +91 -6
- package/package.json +5 -6
- package/src/api-client.js +3 -2
- package/src/commands/foundation.js +5 -3
- package/src/commands/hooks.js +4 -9
- package/src/commands/operations.js +1 -1
- package/src/commands/release-manifest.js +3 -1
- package/src/commands/settings.js +2 -0
- package/src/commands/sms.js +35 -4
- package/src/commands/sso.js +913 -0
- package/src/commands/users-management.js +2 -2
- package/src/commands/users.js +7 -3
- package/src/commands/verifier-keys.js +105 -0
- package/src/login-domain.js +1 -0
- package/src/release-manifest.js +30 -7
- package/src/secret-sink.js +77 -0
- package/src/sms/registration-fields.js +1 -1
- package/src/sso-plan.js +21 -0
- package/src/user-service-instance.js +30 -1
- package/src/users-api.js +3 -2
- package/src/users-import/ids.js +1 -1
- package/templates/saaslayer-foundation-region.yml +10 -2
- package/templates/saaslayer-foundation.yml +33 -5
- 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 +60 -0
- package/vendor/operations/index.js +471 -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,569 @@
|
|
|
1
|
+
// The opt-in local management registry of one user-service instance (plan §4.3a, ServiceManagementTable): owner bootstrap,
|
|
2
|
+
// human grants and machine keys as versioned records under MANAGEMENT#<serviceRef>, serialized on the STATE version.
|
|
3
|
+
'use strict'
|
|
4
|
+
|
|
5
|
+
const crypto = require('crypto')
|
|
6
|
+
const { GetCommand, PutCommand, QueryCommand, TransactWriteCommand } = require('@aws-sdk/lib-dynamodb')
|
|
7
|
+
const { assertPurposes } = require('./purposes')
|
|
8
|
+
|
|
9
|
+
const STATE_SK = 'STATE'
|
|
10
|
+
/** A key moved to retiring stays accepted this long before it may be retired (BFF/import retries, adoption). */
|
|
11
|
+
const RETIRE_AFTER_MS = 5 * 60 * 1000
|
|
12
|
+
/** How long a pending operation holds the registry before another writer may take it over. */
|
|
13
|
+
const DEFAULT_LEASE_MS = 5 * 60 * 1000
|
|
14
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
15
|
+
/** A mutation re-reads and re-plans on a concurrent write this many times before answering busy. */
|
|
16
|
+
const ATTEMPTS = 5
|
|
17
|
+
/** Credential states a presented key is accepted in. */
|
|
18
|
+
const ACCEPTED_STATES = Object.freeze(['next', 'current', 'retiring'])
|
|
19
|
+
|
|
20
|
+
const SERVICE_REF_RE = /^[a-z][a-z0-9-]*(@[a-z][a-z0-9]{0,11})?$/
|
|
21
|
+
const MACHINE_CALLER_RE = /^[a-z][a-z0-9-]{1,62}$/
|
|
22
|
+
const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
|
23
|
+
|
|
24
|
+
/** @type {Record<string, number>} */
|
|
25
|
+
const STATUS_OF = {
|
|
26
|
+
MANAGEMENT_INVALID: 422,
|
|
27
|
+
MANAGEMENT_REASON_REQUIRED: 422,
|
|
28
|
+
MANAGEMENT_BUSY: 409,
|
|
29
|
+
MANAGEMENT_CONFLICT: 409,
|
|
30
|
+
MANAGEMENT_GATE: 409,
|
|
31
|
+
MANAGEMENT_NOT_FOUND: 404,
|
|
32
|
+
MANAGEMENT_UNAVAILABLE: 503,
|
|
33
|
+
MANAGEMENT_ACCOUNT_UNTRUSTED: 409,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {keyof typeof STATUS_OF} code
|
|
38
|
+
* @param {string} message
|
|
39
|
+
* @returns {Error & { code: string, statusCode: number }}
|
|
40
|
+
*/
|
|
41
|
+
function managementError(code, message) {
|
|
42
|
+
return Object.assign(new Error(message), { code, statusCode: STATUS_OF[code] })
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The registry partition of one service instance: MANAGEMENT#<serviceRef> (service or service@instance).
|
|
47
|
+
* @param {string} serviceRef
|
|
48
|
+
*/
|
|
49
|
+
function managementPK(serviceRef) {
|
|
50
|
+
if (!SERVICE_REF_RE.test(String(serviceRef))) throw new Error(`invalid service ref "${serviceRef}"`)
|
|
51
|
+
return `MANAGEMENT#${serviceRef}`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param {'human'|'machine'} callerType @param {string} callerId */
|
|
55
|
+
const callerSK = (callerType, callerId) => `CALLER#${callerType}#${callerId}`
|
|
56
|
+
/** @param {string} keyId */
|
|
57
|
+
const tombstoneSK = (keyId) => `TOMBSTONE#${keyId}`
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The SHA-256 digest a registry credential carries for a raw key, base64url.
|
|
61
|
+
* @param {string} raw
|
|
62
|
+
*/
|
|
63
|
+
function keyDigest(raw) {
|
|
64
|
+
return crypto.createHash('sha256').update(String(raw), 'utf8').digest('base64url')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @param {string} a @param {string} b */
|
|
68
|
+
function digestsEqual(a, b) {
|
|
69
|
+
const ab = Buffer.from(String(a))
|
|
70
|
+
const bb = Buffer.from(String(b))
|
|
71
|
+
return ab.length === bb.length && crypto.timingSafeEqual(ab, bb)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @param {unknown} reason */
|
|
75
|
+
const reasonOf = (reason) => (typeof reason === 'string' && reason.trim() ? reason.trim() : null)
|
|
76
|
+
|
|
77
|
+
/** @param {unknown} suid */
|
|
78
|
+
function assertPrincipal(suid) {
|
|
79
|
+
if (typeof suid !== 'string' || !suid.trim() || suid.length > 256 || suid.includes('#')) throw managementError('MANAGEMENT_INVALID', 'a principal is a non-empty suid (at most 256 chars, no #)')
|
|
80
|
+
return suid.trim()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** @param {unknown} sub the grantee account's Cognito sub @param {string} suid */
|
|
84
|
+
function assertAccountSub(sub, suid) {
|
|
85
|
+
if (typeof sub !== 'string' || !sub.trim() || sub.length > 256) throw managementError('MANAGEMENT_INVALID', `${suid}'s grant needs the sub of the own-pool account it is bound to`)
|
|
86
|
+
return sub.trim()
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** @param {unknown} callerId */
|
|
90
|
+
function assertMachineCaller(callerId) {
|
|
91
|
+
if (typeof callerId !== 'string' || !MACHINE_CALLER_RE.test(callerId)) throw managementError('MANAGEMENT_INVALID', 'a caller id is 2-63 chars: lowercase letters, digits and hyphens, letter first')
|
|
92
|
+
return callerId
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {unknown} err */
|
|
96
|
+
const isCancelled = (err) => Boolean(err && /** @type {{ name?: string }} */ (err).name === 'TransactionCanceledException')
|
|
97
|
+
|
|
98
|
+
/** @param {string[]} a @param {string[]} b */
|
|
99
|
+
const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x))
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* @typedef {{ keyId: string, sha256: string, state: 'next'|'current'|'retiring', introducedAt: string, activatedAt?: string, retireAfter?: string }} Credential
|
|
103
|
+
* @typedef {{ pk: string, sk: string, callerType: 'human'|'machine', callerId: string, principalId?: string, principalSub?: string, email?: string,
|
|
104
|
+
* purposes: string[], status: 'active'|'revoked', version: number, credentials: Credential[], createdAt: string, updatedAt: string,
|
|
105
|
+
* lastChange: { action: string, reason?: string, actor: unknown, at: string } }} CallerRecord
|
|
106
|
+
* @typedef {{ op: 'introduce', callerId: string, keyId: string, purposes: string[], startedAt: string, leaseUntil: string }} PendingOp
|
|
107
|
+
* @typedef {{ pk: string, sk: string, version: number, generation: number, owners: string[], pendingOp: PendingOp|null, updatedAt: string }} StateRecord
|
|
108
|
+
* @typedef {{ put: (keyId: string, raw: string) => Promise<void>, get: (keyId: string) => Promise<string|null>, remove: (keyId: string) => Promise<void> }} MaterialStore
|
|
109
|
+
* durable owner-only storage of a key's raw value while it is pending (standalone: a create-only SecureString)
|
|
110
|
+
*/
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @param {{ doc: { send: (cmd: any) => Promise<any> }, tableName: string, serviceRef: string, now?: () => number,
|
|
114
|
+
* random?: (bytes: number) => Buffer, leaseMs?: number }} deps
|
|
115
|
+
*/
|
|
116
|
+
function createManagementRegistry(deps) {
|
|
117
|
+
const { doc, tableName } = deps
|
|
118
|
+
const pk = managementPK(deps.serviceRef)
|
|
119
|
+
const now = deps.now || Date.now
|
|
120
|
+
const random = deps.random || crypto.randomBytes
|
|
121
|
+
const leaseMs = deps.leaseMs || DEFAULT_LEASE_MS
|
|
122
|
+
const iso = () => new Date(now()).toISOString()
|
|
123
|
+
|
|
124
|
+
/** @param {string} sk @returns {Promise<any>} */
|
|
125
|
+
async function read(sk) {
|
|
126
|
+
let res
|
|
127
|
+
try {
|
|
128
|
+
res = await doc.send(new GetCommand({ TableName: tableName, Key: { pk, sk }, ConsistentRead: true }))
|
|
129
|
+
} catch (err) {
|
|
130
|
+
throw managementError('MANAGEMENT_UNAVAILABLE', `the management registry cannot be read: ${/** @type {Error} */ (err).message}`)
|
|
131
|
+
}
|
|
132
|
+
return res.Item || null
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* One caller's record, read strongly consistent (D12): a revoke is refused at the next check. Throws
|
|
137
|
+
* MANAGEMENT_UNAVAILABLE when the registry cannot be read (callers fail closed).
|
|
138
|
+
* @param {'human'|'machine'} callerType @param {string} callerId
|
|
139
|
+
* @returns {Promise<CallerRecord|null>}
|
|
140
|
+
*/
|
|
141
|
+
async function readCaller(callerType, callerId) {
|
|
142
|
+
return read(callerSK(callerType, callerId))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** @param {string} keyId @returns {Promise<any>} */
|
|
146
|
+
const readTombstone = (keyId) => read(tombstoneSK(keyId))
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* @param {Record<string, any>} item @param {number|null} version the version read, null when the item was absent
|
|
150
|
+
*/
|
|
151
|
+
const guardedPut = (item, version) => ({
|
|
152
|
+
Put: {
|
|
153
|
+
TableName: tableName,
|
|
154
|
+
Item: item,
|
|
155
|
+
...(version === null
|
|
156
|
+
? { ConditionExpression: 'attribute_not_exists(pk)' }
|
|
157
|
+
: { ConditionExpression: '#version = :version', ExpressionAttributeNames: { '#version': 'version' }, ExpressionAttributeValues: { ':version': version } }),
|
|
158
|
+
},
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Plan against strongly read state and commit it atomically with the STATE version bump; a concurrent writer makes it
|
|
163
|
+
* re-read and re-plan. A plan returning null writes nothing.
|
|
164
|
+
* @template T
|
|
165
|
+
* @param {(state: StateRecord|null) => Promise<{ state?: Partial<StateRecord>, callers?: Array<{ record: Record<string, any>, readVersion: number|null }>, tombstones?: Array<Record<string, any>>, result: T }|{ result: T, noop: true }>} plan
|
|
166
|
+
* @returns {Promise<T>}
|
|
167
|
+
*/
|
|
168
|
+
async function mutate(plan) {
|
|
169
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
170
|
+
const state = /** @type {StateRecord|null} */ (await read(STATE_SK))
|
|
171
|
+
const planned = await plan(state)
|
|
172
|
+
if ('noop' in planned) return planned.result
|
|
173
|
+
const at = iso()
|
|
174
|
+
const nextState = {
|
|
175
|
+
owners: [],
|
|
176
|
+
pendingOp: null,
|
|
177
|
+
...(state || {}),
|
|
178
|
+
...(planned.state || {}),
|
|
179
|
+
pk,
|
|
180
|
+
sk: STATE_SK,
|
|
181
|
+
version: state ? state.version + 1 : 1,
|
|
182
|
+
generation: state ? state.generation + 1 : 1,
|
|
183
|
+
updatedAt: at,
|
|
184
|
+
}
|
|
185
|
+
const items = [
|
|
186
|
+
guardedPut(nextState, state ? state.version : null),
|
|
187
|
+
...(planned.callers || []).map((c) => guardedPut(c.record, c.readVersion)),
|
|
188
|
+
...(planned.tombstones || []).map((t) => guardedPut(t, null)),
|
|
189
|
+
]
|
|
190
|
+
try {
|
|
191
|
+
await doc.send(new TransactWriteCommand({ TransactItems: items }))
|
|
192
|
+
return planned.result
|
|
193
|
+
} catch (err) {
|
|
194
|
+
if (!isCancelled(err)) throw err
|
|
195
|
+
if (attempt >= ATTEMPTS) throw managementError('MANAGEMENT_BUSY', 'the management registry kept changing; retry')
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* @param {CallerRecord|null} from @param {Partial<CallerRecord>} set
|
|
202
|
+
* @param {{ action: string, reason?: string|null, actor: unknown }} change
|
|
203
|
+
* @returns {CallerRecord}
|
|
204
|
+
*/
|
|
205
|
+
function nextCaller(from, set, change) {
|
|
206
|
+
const at = iso()
|
|
207
|
+
const lastChange = { action: change.action, ...(change.reason ? { reason: change.reason } : {}), actor: change.actor, at }
|
|
208
|
+
return /** @type {CallerRecord} */ ({
|
|
209
|
+
...(from || { createdAt: at, credentials: [] }),
|
|
210
|
+
...set,
|
|
211
|
+
pk,
|
|
212
|
+
version: from ? from.version + 1 : 1,
|
|
213
|
+
updatedAt: at,
|
|
214
|
+
lastChange,
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* A grant is bound to the own-pool account (its Cognito sub) it was made for: only that account's tokens use it.
|
|
220
|
+
* @param {{ suid: string, sub: string, email?: string, purposes: string[] }} grantee
|
|
221
|
+
* @param {{ action: string, reason?: string|null, actor: unknown }} change
|
|
222
|
+
*/
|
|
223
|
+
const newHumanGrant = (grantee, change) => nextCaller(null, {
|
|
224
|
+
sk: callerSK('human', grantee.suid),
|
|
225
|
+
callerType: 'human',
|
|
226
|
+
callerId: grantee.suid,
|
|
227
|
+
principalId: grantee.suid,
|
|
228
|
+
principalSub: grantee.sub,
|
|
229
|
+
...(grantee.email ? { email: grantee.email } : {}),
|
|
230
|
+
purposes: grantee.purposes,
|
|
231
|
+
status: 'active',
|
|
232
|
+
}, change)
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Bootstrap the root owners (create-only, idempotent): each owner without a record gets an active grant bound to its
|
|
236
|
+
* account's sub; an existing active one is unchanged and a revoked one stays revoked unless this is an explicit recovery
|
|
237
|
+
* with a reason. Adding a root owner after the first bootstrap needs a reason. An active grant bound to no account is
|
|
238
|
+
* bound with a reason ('rebound', else 'unbound'); one bound to another account is moved only by an explicit recovery
|
|
239
|
+
* ('conflict' otherwise).
|
|
240
|
+
* @param {{ owners: Array<{ suid: string, sub: string, email?: string, purposes: string[] }>, actor: unknown, reason?: string, recover?: boolean }} input
|
|
241
|
+
*/
|
|
242
|
+
async function bootstrap({ owners, actor, reason, recover }) {
|
|
243
|
+
if (!Array.isArray(owners) || owners.length === 0) throw managementError('MANAGEMENT_INVALID', 'bootstrap names at least one owner')
|
|
244
|
+
const why = reasonOf(reason)
|
|
245
|
+
if (recover && !why) throw managementError('MANAGEMENT_REASON_REQUIRED', 'root recovery requires a reason')
|
|
246
|
+
const seen = new Set()
|
|
247
|
+
const wanted = owners.map((o) => {
|
|
248
|
+
const suid = assertPrincipal(o && o.suid)
|
|
249
|
+
if (seen.has(suid)) throw managementError('MANAGEMENT_INVALID', `owner ${suid} is named more than once`)
|
|
250
|
+
seen.add(suid)
|
|
251
|
+
const email = typeof o.email === 'string' && o.email.trim() ? o.email.trim().toLowerCase() : undefined
|
|
252
|
+
if (email && !EMAIL_SHAPE.test(email)) throw managementError('MANAGEMENT_INVALID', `owner ${suid} needs a valid email`)
|
|
253
|
+
return { suid, sub: assertAccountSub(o.sub, suid), ...(email ? { email } : {}), purposes: assertPurposes(o.purposes, 'human') }
|
|
254
|
+
})
|
|
255
|
+
return mutate(async (state) => {
|
|
256
|
+
const roots = state ? state.owners || [] : []
|
|
257
|
+
const added = wanted.filter((o) => !roots.includes(o.suid))
|
|
258
|
+
if (roots.length && added.length && !why) throw managementError('MANAGEMENT_REASON_REQUIRED', `this instance already has root owners; adding ${added.map((o) => o.suid).join(', ')} requires a reason`)
|
|
259
|
+
/** @type {Array<{ record: Record<string, any>, readVersion: number|null }>} */
|
|
260
|
+
const callers = []
|
|
261
|
+
const outcomes = []
|
|
262
|
+
for (const owner of wanted) {
|
|
263
|
+
const current = await readCaller('human', owner.suid)
|
|
264
|
+
if (!current) {
|
|
265
|
+
callers.push({ record: newHumanGrant(owner, { action: 'bootstrap', reason: why, actor }), readVersion: null })
|
|
266
|
+
outcomes.push({ suid: owner.suid, outcome: 'granted' })
|
|
267
|
+
} else if (current.status === 'active' && current.principalSub === owner.sub) {
|
|
268
|
+
outcomes.push({ suid: owner.suid, outcome: 'unchanged' })
|
|
269
|
+
} else if (current.status === 'active' && !recover) {
|
|
270
|
+
const bindable = !current.principalSub && why
|
|
271
|
+
if (bindable) callers.push({ record: nextCaller(current, { principalSub: owner.sub }, { action: 'bootstrap.rebound', reason: why, actor }), readVersion: current.version })
|
|
272
|
+
outcomes.push({ suid: owner.suid, outcome: bindable ? 'rebound' : current.principalSub ? 'conflict' : 'unbound' })
|
|
273
|
+
} else if (current.status === 'active') {
|
|
274
|
+
callers.push({ record: nextCaller(current, { principalSub: owner.sub }, { action: 'bootstrap.rebound', reason: why, actor }), readVersion: current.version })
|
|
275
|
+
outcomes.push({ suid: owner.suid, outcome: 'rebound' })
|
|
276
|
+
} else if (recover) {
|
|
277
|
+
callers.push({ record: nextCaller(current, { status: 'active', principalSub: owner.sub, purposes: owner.purposes }, { action: 'bootstrap.recovered', reason: why, actor }), readVersion: current.version })
|
|
278
|
+
outcomes.push({ suid: owner.suid, outcome: 'recovered' })
|
|
279
|
+
} else {
|
|
280
|
+
outcomes.push({ suid: owner.suid, outcome: 'revoked' })
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
const result = { owners: outcomes }
|
|
284
|
+
if (callers.length === 0 && added.length === 0) return { result, noop: true }
|
|
285
|
+
return { state: { owners: [...roots, ...added.map((o) => o.suid)] }, callers, result }
|
|
286
|
+
})
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Grant (or change) a local human's purposes, bound to the account (sub) the grantee's suid resolves to. Reactivating a
|
|
291
|
+
* revoked grant is an explicit recovery, and binding a grant to another account (or one bound to none) a re-bind: both
|
|
292
|
+
* require a reason.
|
|
293
|
+
* @param {{ principal: string, sub: string, email?: string, purposes: string[], actor: unknown, reason?: string }} input
|
|
294
|
+
*/
|
|
295
|
+
async function grant({ principal, sub, email, purposes, actor, reason }) {
|
|
296
|
+
const suid = assertPrincipal(principal)
|
|
297
|
+
const accountSub = assertAccountSub(sub, suid)
|
|
298
|
+
const held = assertPurposes(purposes, 'human')
|
|
299
|
+
const why = reasonOf(reason)
|
|
300
|
+
return mutate(async () => {
|
|
301
|
+
const current = await readCaller('human', suid)
|
|
302
|
+
if (!current) {
|
|
303
|
+
return { callers: [{ record: newHumanGrant({ suid, sub: accountSub, ...(email ? { email } : {}), purposes: held }, { action: 'grant', reason: why, actor }), readVersion: null }], result: { principal: suid, outcome: 'granted' } }
|
|
304
|
+
}
|
|
305
|
+
if (current.status === 'revoked') {
|
|
306
|
+
if (!why) throw managementError('MANAGEMENT_REASON_REQUIRED', `${suid}'s grant was revoked; granting it again is a recovery and requires a reason`)
|
|
307
|
+
return { callers: [{ record: nextCaller(current, { status: 'active', principalSub: accountSub, purposes: held }, { action: 'grant.recovered', reason: why, actor }), readVersion: current.version }], result: { principal: suid, outcome: 'recovered' } }
|
|
308
|
+
}
|
|
309
|
+
if (current.principalSub !== accountSub) {
|
|
310
|
+
if (!why) throw managementError('MANAGEMENT_REASON_REQUIRED', `${suid}'s grant is bound to ${current.principalSub ? 'another account' : 'no account'}; binding it to this one requires a reason`)
|
|
311
|
+
return { callers: [{ record: nextCaller(current, { principalSub: accountSub, purposes: held }, { action: 'grant.rebound', reason: why, actor }), readVersion: current.version }], result: { principal: suid, outcome: 'rebound' } }
|
|
312
|
+
}
|
|
313
|
+
if (sameSet(current.purposes, held)) return { result: { principal: suid, outcome: 'unchanged' }, noop: true }
|
|
314
|
+
return { callers: [{ record: nextCaller(current, { purposes: held }, { action: 'grant', reason: why, actor }), readVersion: current.version }], result: { principal: suid, outcome: 'updated' } }
|
|
315
|
+
})
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Revoke a local human's grant: the record stays, inactive, at a higher version (no replay restores it).
|
|
320
|
+
* @param {{ principal: string, reason?: string, actor: unknown }} input
|
|
321
|
+
*/
|
|
322
|
+
async function revokeGrant({ principal, reason, actor }) {
|
|
323
|
+
const suid = assertPrincipal(principal)
|
|
324
|
+
const why = reasonOf(reason)
|
|
325
|
+
if (!why) throw managementError('MANAGEMENT_REASON_REQUIRED', 'revoking a grant requires a reason')
|
|
326
|
+
return mutate(async () => {
|
|
327
|
+
const current = await readCaller('human', suid)
|
|
328
|
+
if (!current) throw managementError('MANAGEMENT_NOT_FOUND', `${suid} holds no grant`)
|
|
329
|
+
if (current.status === 'revoked') return { result: { principal: suid, outcome: 'unchanged' }, noop: true }
|
|
330
|
+
return { callers: [{ record: nextCaller(current, { status: 'revoked' }, { action: 'grant.revoked', reason: why, actor }), readVersion: current.version }], result: { principal: suid, outcome: 'revoked' } }
|
|
331
|
+
})
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** A fresh key id: mk_ + 16 hex. */
|
|
335
|
+
const mintKeyId = () => `mk_${random(8).toString('hex')}`
|
|
336
|
+
/** A fresh raw key: 32 random bytes, base64url. */
|
|
337
|
+
const mintKey = () => random(32).toString('base64url')
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Introduce a machine key as pending (next). With keyId + key the caller supplies durable pending material (issueKey);
|
|
341
|
+
* with keyId + sha256 the raw value is held elsewhere (the control plane, managed mode) and none is returned; otherwise
|
|
342
|
+
* both are minted here. The raw value is never stored in the registry.
|
|
343
|
+
* @param {{ callerId: string, purposes: string[], actor: unknown, keyId?: string, key?: string, sha256?: string }} input
|
|
344
|
+
* @returns {Promise<{ callerId: string, keyId: string, key?: string }>}
|
|
345
|
+
*/
|
|
346
|
+
async function introduceKey({ callerId, purposes, actor, keyId, key, sha256: digest }) {
|
|
347
|
+
const id = assertMachineCaller(callerId)
|
|
348
|
+
const held = assertPurposes(purposes, 'machine')
|
|
349
|
+
if (digest && (!keyId || key)) throw managementError('MANAGEMENT_INVALID', 'a key introduced by digest names its key id and carries no raw value')
|
|
350
|
+
if (keyId && !/^mk_[0-9a-f]{16}$/.test(keyId)) throw managementError('MANAGEMENT_INVALID', 'a key id is mk_ followed by 16 hex digits')
|
|
351
|
+
if (digest && !/^[A-Za-z0-9_-]{43}$/.test(digest)) throw managementError('MANAGEMENT_INVALID', 'a key digest is a base64url SHA-256')
|
|
352
|
+
const newKeyId = keyId || mintKeyId()
|
|
353
|
+
const raw = digest ? null : key || mintKey()
|
|
354
|
+
const sha256 = digest || keyDigest(/** @type {string} */ (raw))
|
|
355
|
+
return mutate(async (state) => {
|
|
356
|
+
if (await readTombstone(newKeyId)) throw managementError('MANAGEMENT_CONFLICT', `${newKeyId} is a dead key id and is never introduced again`)
|
|
357
|
+
const current = await readCaller('machine', id)
|
|
358
|
+
if (current && !sameSet(current.purposes, held)) throw managementError('MANAGEMENT_INVALID', `${id} holds ${current.purposes.join(', ')}; a key for other purposes is another caller`)
|
|
359
|
+
if (current && current.credentials.some((c) => c.state === 'next')) throw managementError('MANAGEMENT_BUSY', `${id} already has a pending key; activate or revoke it first`)
|
|
360
|
+
/** @type {Credential} */
|
|
361
|
+
const credential = { keyId: newKeyId, sha256, state: 'next', introducedAt: iso() }
|
|
362
|
+
const record = current
|
|
363
|
+
? nextCaller(current, { credentials: [...current.credentials, credential] }, { action: 'key.introduced', actor })
|
|
364
|
+
: nextCaller(null, { sk: callerSK('machine', id), callerType: 'machine', callerId: id, purposes: held, status: 'active', credentials: [credential] }, { action: 'key.introduced', actor })
|
|
365
|
+
const clears = state && state.pendingOp && state.pendingOp.keyId === newKeyId
|
|
366
|
+
return { ...(clears ? { state: { pendingOp: null } } : {}), callers: [{ record, readVersion: current ? current.version : null }], result: { callerId: id, keyId: newKeyId, ...(raw ? { key: raw } : {}) } }
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Issue a machine key with its raw value durable before it is accepted: reserve the registry (pending operation), write
|
|
372
|
+
* the raw value create-only to the owner's material store, then introduce it. A retry after any crash resumes the same
|
|
373
|
+
* key id and raw value; a retry after success re-outputs the still-pending key. A live lease of another caller is busy.
|
|
374
|
+
* @param {{ callerId: string, purposes: string[], actor: unknown, material: MaterialStore }} input
|
|
375
|
+
* @returns {Promise<{ callerId: string, keyId: string, key: string, reused: boolean }>}
|
|
376
|
+
*/
|
|
377
|
+
async function issueKey({ callerId, purposes, actor, material }) {
|
|
378
|
+
const id = assertMachineCaller(callerId)
|
|
379
|
+
const held = assertPurposes(purposes, 'machine')
|
|
380
|
+
const existing = await readCaller('machine', id)
|
|
381
|
+
const pendingKey = existing && existing.credentials.find((c) => c.state === 'next')
|
|
382
|
+
if (pendingKey) {
|
|
383
|
+
const raw = await material.get(pendingKey.keyId)
|
|
384
|
+
if (!raw || !digestsEqual(keyDigest(raw), pendingKey.sha256)) throw managementError('MANAGEMENT_BUSY', `${id} has a pending key ${pendingKey.keyId} whose material is gone; activate or revoke it first`)
|
|
385
|
+
return { callerId: id, keyId: pendingKey.keyId, key: raw, reused: true }
|
|
386
|
+
}
|
|
387
|
+
const reserved = await mutate(async (state) => {
|
|
388
|
+
const op = state && state.pendingOp
|
|
389
|
+
const live = op && Date.parse(op.leaseUntil) > now()
|
|
390
|
+
if (live && op.callerId !== id) throw managementError('MANAGEMENT_BUSY', `another management operation (${op.op} for ${op.callerId}) is in progress until ${op.leaseUntil}`)
|
|
391
|
+
const keyId = op && op.callerId === id && op.op === 'introduce' ? op.keyId : mintKeyId()
|
|
392
|
+
/** @type {PendingOp} */
|
|
393
|
+
const pendingOp = { op: 'introduce', callerId: id, keyId, purposes: held, startedAt: iso(), leaseUntil: new Date(now() + leaseMs).toISOString() }
|
|
394
|
+
return { state: { pendingOp }, result: pendingOp }
|
|
395
|
+
})
|
|
396
|
+
let raw = await material.get(reserved.keyId)
|
|
397
|
+
if (!raw) {
|
|
398
|
+
const minted = mintKey()
|
|
399
|
+
try {
|
|
400
|
+
await material.put(reserved.keyId, minted)
|
|
401
|
+
raw = minted
|
|
402
|
+
} catch (err) {
|
|
403
|
+
if (!err || /** @type {{ name?: string }} */ (err).name !== 'ParameterAlreadyExists') throw err
|
|
404
|
+
raw = await material.get(reserved.keyId)
|
|
405
|
+
if (!raw) throw err
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
const introduced = await introduceKey({ callerId: id, purposes: held, actor, keyId: reserved.keyId, key: raw })
|
|
409
|
+
return { ...introduced, reused: false }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* @param {string} callerId @param {string} keyId
|
|
414
|
+
* @returns {Promise<{ current: CallerRecord, credential: Credential }>}
|
|
415
|
+
*/
|
|
416
|
+
async function credentialOf(callerId, keyId) {
|
|
417
|
+
const current = await readCaller('machine', assertMachineCaller(callerId))
|
|
418
|
+
const credential = current && current.credentials.find((c) => c.keyId === keyId)
|
|
419
|
+
if (!current || !credential) throw managementError('MANAGEMENT_NOT_FOUND', `${callerId} has no key ${keyId}`)
|
|
420
|
+
return { current, credential }
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** @param {MaterialStore|undefined} material @param {string} keyId */
|
|
424
|
+
async function dropMaterial(material, keyId) {
|
|
425
|
+
if (!material) return true
|
|
426
|
+
try {
|
|
427
|
+
await material.remove(keyId)
|
|
428
|
+
return true
|
|
429
|
+
} catch {
|
|
430
|
+
return false
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Make a pending key current; the previous current key starts retiring (still accepted for the overlap).
|
|
436
|
+
* @param {{ callerId: string, keyId: string, actor: unknown, material?: MaterialStore }} input
|
|
437
|
+
*/
|
|
438
|
+
async function activateKey({ callerId, keyId, actor, material }) {
|
|
439
|
+
const result = await mutate(async () => {
|
|
440
|
+
const { current, credential } = await credentialOf(callerId, keyId)
|
|
441
|
+
if (credential.state !== 'next') throw managementError('MANAGEMENT_GATE', `${keyId} is ${credential.state}; only a pending key is activated`)
|
|
442
|
+
const at = iso()
|
|
443
|
+
const retireAfter = new Date(now() + RETIRE_AFTER_MS).toISOString()
|
|
444
|
+
const credentials = current.credentials.map((c) => {
|
|
445
|
+
if (c.keyId === keyId) return { ...c, state: /** @type {const} */ ('current'), activatedAt: at }
|
|
446
|
+
if (c.state === 'current') return { ...c, state: /** @type {const} */ ('retiring'), retireAfter }
|
|
447
|
+
return c
|
|
448
|
+
})
|
|
449
|
+
return { callers: [{ record: nextCaller(current, { credentials }, { action: 'key.activated', actor }), readVersion: current.version }], result: { callerId, keyId, state: 'current' } }
|
|
450
|
+
})
|
|
451
|
+
return { ...result, materialRemoved: await dropMaterial(material, keyId) }
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Retire a retiring key once its overlap has passed: removed and tombstoned.
|
|
456
|
+
* @param {{ callerId: string, keyId: string, actor: unknown, material?: MaterialStore }} input
|
|
457
|
+
*/
|
|
458
|
+
async function retireKey({ callerId, keyId, actor, material }) {
|
|
459
|
+
const result = await mutate(async () => {
|
|
460
|
+
const { current, credential } = await credentialOf(callerId, keyId)
|
|
461
|
+
if (credential.state !== 'retiring') throw managementError('MANAGEMENT_GATE', `${keyId} is ${credential.state}; activate a replacement first (or revoke it)`)
|
|
462
|
+
if (Date.parse(/** @type {string} */ (credential.retireAfter)) > now()) throw managementError('MANAGEMENT_GATE', `${keyId} may be retired from ${credential.retireAfter}`)
|
|
463
|
+
return removal(current, credential, 'retired', actor, 'key.retired')
|
|
464
|
+
})
|
|
465
|
+
return { ...result, materialRemoved: await dropMaterial(material, keyId) }
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Revoke a key now (emergency, reason required): removed and tombstoned; the next check refuses it.
|
|
470
|
+
* @param {{ callerId: string, keyId: string, reason?: string, actor: unknown, material?: MaterialStore }} input
|
|
471
|
+
*/
|
|
472
|
+
async function revokeKey({ callerId, keyId, reason, actor, material }) {
|
|
473
|
+
const why = reasonOf(reason)
|
|
474
|
+
if (!why) throw managementError('MANAGEMENT_REASON_REQUIRED', 'revoking a key requires a reason')
|
|
475
|
+
const result = await mutate(async () => {
|
|
476
|
+
if (await readTombstone(keyId)) return { result: { callerId, keyId, state: 'revoked', outcome: 'unchanged' }, noop: true }
|
|
477
|
+
const { current, credential } = await credentialOf(callerId, keyId)
|
|
478
|
+
return removal(current, credential, why, actor, 'key.revoked')
|
|
479
|
+
})
|
|
480
|
+
return { ...result, materialRemoved: await dropMaterial(material, keyId) }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* @param {CallerRecord} current @param {Credential} credential @param {string} reason @param {unknown} actor @param {string} action
|
|
485
|
+
*/
|
|
486
|
+
function removal(current, credential, reason, actor, action) {
|
|
487
|
+
const record = nextCaller(current, { credentials: current.credentials.filter((c) => c.keyId !== credential.keyId) }, { action, ...(action === 'key.revoked' ? { reason } : {}), actor })
|
|
488
|
+
const tombstone = { pk, sk: tombstoneSK(credential.keyId), keyId: credential.keyId, callerId: current.callerId, sha256: credential.sha256, reason, actor, at: iso() }
|
|
489
|
+
return { callers: [{ record, readVersion: current.version }], tombstones: [tombstone], result: { callerId: current.callerId, keyId: credential.keyId, state: action === 'key.revoked' ? 'revoked' : 'retired' } }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* The registry as owners see it: state, callers with key ids/states/age, dead key ids. Never a hash or raw value.
|
|
494
|
+
*/
|
|
495
|
+
async function status() {
|
|
496
|
+
let items
|
|
497
|
+
try {
|
|
498
|
+
const res = await doc.send(new QueryCommand({ TableName: tableName, KeyConditionExpression: 'pk = :pk', ExpressionAttributeValues: { ':pk': pk }, ConsistentRead: true }))
|
|
499
|
+
items = res.Items || []
|
|
500
|
+
} catch (err) {
|
|
501
|
+
throw managementError('MANAGEMENT_UNAVAILABLE', `the management registry cannot be read: ${/** @type {Error} */ (err).message}`)
|
|
502
|
+
}
|
|
503
|
+
const state = items.find((i) => i.sk === STATE_SK)
|
|
504
|
+
const ageDays = (/** @type {string} */ at) => Math.max(0, Math.floor((now() - Date.parse(at)) / DAY_MS))
|
|
505
|
+
return {
|
|
506
|
+
serviceRef: deps.serviceRef,
|
|
507
|
+
state: state ? { version: state.version, generation: state.generation, owners: state.owners || [], pendingOp: state.pendingOp || null } : null,
|
|
508
|
+
callers: items.filter((i) => String(i.sk).startsWith('CALLER#')).map((c) => ({
|
|
509
|
+
callerType: c.callerType,
|
|
510
|
+
callerId: c.callerId,
|
|
511
|
+
...(c.principalId ? { principalId: c.principalId } : {}),
|
|
512
|
+
...(c.email ? { email: c.email } : {}),
|
|
513
|
+
purposes: c.purposes,
|
|
514
|
+
status: c.status,
|
|
515
|
+
version: c.version,
|
|
516
|
+
credentials: (c.credentials || []).map((/** @type {Credential} */ k) => ({
|
|
517
|
+
keyId: k.keyId, state: k.state, introducedAt: k.introducedAt, ...(k.activatedAt ? { activatedAt: k.activatedAt } : {}), ...(k.retireAfter ? { retireAfter: k.retireAfter } : {}), ageDays: ageDays(k.introducedAt),
|
|
518
|
+
})),
|
|
519
|
+
lastChange: c.lastChange,
|
|
520
|
+
})),
|
|
521
|
+
tombstones: items.filter((i) => String(i.sk).startsWith('TOMBSTONE#')).map((t) => ({ keyId: t.keyId, callerId: t.callerId, reason: t.reason, at: t.at })),
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
return { serviceRef: deps.serviceRef, readCaller, status, bootstrap, grant, revokeGrant, introduceKey, issueKey, activateKey, retireKey, revokeKey }
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Verify a presented machine key for the caller id that selected its record: the record must be active and hold an
|
|
530
|
+
* accepted credential whose digest matches (constant time over every credential).
|
|
531
|
+
* @param {{ readCaller: (t: 'human'|'machine', id: string) => Promise<CallerRecord|null> }} registry
|
|
532
|
+
* @param {string} callerId
|
|
533
|
+
* @param {string} presented
|
|
534
|
+
* @returns {Promise<{ status: 'ok', caller: { callerType: 'machine', callerId: string, keyId: string, purposes: string[] } } | { status: 'unknown' }>}
|
|
535
|
+
*/
|
|
536
|
+
async function verifyMachineKey(registry, callerId, presented) {
|
|
537
|
+
if (!presented || !MACHINE_CALLER_RE.test(String(callerId))) return { status: 'unknown' }
|
|
538
|
+
const record = await registry.readCaller('machine', callerId)
|
|
539
|
+
if (!record || record.status !== 'active') return { status: 'unknown' }
|
|
540
|
+
const digest = keyDigest(presented)
|
|
541
|
+
let found = null
|
|
542
|
+
for (const c of record.credentials || []) {
|
|
543
|
+
if (digestsEqual(c.sha256, digest) && ACCEPTED_STATES.includes(c.state) && !found) found = c
|
|
544
|
+
}
|
|
545
|
+
if (!found) return { status: 'unknown' }
|
|
546
|
+
return { status: 'ok', caller: { callerType: 'machine', callerId: record.callerId, keyId: found.keyId, purposes: record.purposes } }
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* The active local grant of a verified own-pool human: the token's suid selects the record, and the account the grant was
|
|
551
|
+
* bound to must be the token's: its sub, or on an opted-in deployment any credential the account's bindings own (a grant
|
|
552
|
+
* bound through one sign-in method holds for the account's other methods). A grant bound to no account is unbound (refused
|
|
553
|
+
* until re-bound); anything else is unknown.
|
|
554
|
+
* @param {{ readCaller: (t: 'human'|'machine', id: string) => Promise<CallerRecord|null> }} registry
|
|
555
|
+
* @param {string} suid
|
|
556
|
+
* @param {string} sub the verified token's Cognito sub
|
|
557
|
+
* @param {string[]} [ownedSubs] every Cognito sub the token's account owns (its credential bindings); default: the token's sub
|
|
558
|
+
* @returns {Promise<{ status: 'ok', caller: { callerType: 'human', callerId: string, purposes: string[] } } | { status: 'unknown'|'unbound' }>}
|
|
559
|
+
*/
|
|
560
|
+
async function verifyHumanGrant(registry, suid, sub, ownedSubs = [sub]) {
|
|
561
|
+
if (!suid || String(suid).includes('#') || !sub) return { status: 'unknown' }
|
|
562
|
+
const record = await registry.readCaller('human', suid)
|
|
563
|
+
if (!record || record.status !== 'active') return { status: 'unknown' }
|
|
564
|
+
if (!record.principalSub) return { status: 'unbound' }
|
|
565
|
+
if (!ownedSubs.includes(record.principalSub)) return { status: 'unknown' }
|
|
566
|
+
return { status: 'ok', caller: { callerType: 'human', callerId: record.callerId, purposes: record.purposes } }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
module.exports = { createManagementRegistry, verifyMachineKey, verifyHumanGrant, managementPK, keyDigest, managementError, RETIRE_AFTER_MS }
|