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,237 @@
|
|
|
1
|
+
// Direct-mode compatibility contract: the permission-doc and registry-snapshot formats this engine reads, the
|
|
2
|
+
// decision-engine contract version, which @saaslayer/permissions releases read what, and the preflight over declared readers.
|
|
3
|
+
const { READABLE_SSO_CLAIMS } = require('./sso-claims')
|
|
4
|
+
const { READABLE_ACCOUNT_STATUS } = require('./account-status')
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Decision semantics version shared by the service's HTTP decisions and direct-mode readers (bump = parity break).
|
|
8
|
+
* 2: the impersonation session ceiling (impersonation-session.js) applies before evaluation in both transports.
|
|
9
|
+
*/
|
|
10
|
+
const DECISION_ENGINE_CONTRACT = 2
|
|
11
|
+
const READER_PACKAGE = '@saaslayer/permissions'
|
|
12
|
+
|
|
13
|
+
/** Formats this engine-core reads. A permissions doc without `schemaVersion` and a snapshot without `format` are format 1. */
|
|
14
|
+
const READABLE_FORMATS = Object.freeze({
|
|
15
|
+
permissionDoc: Object.freeze([1, 2]),
|
|
16
|
+
registrySnapshot: Object.freeze([1]),
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
/** SSO contracts this engine reads: the token claim contract (sso-claims.js) and the live account-status answer (account-status.js). */
|
|
20
|
+
const READABLE_CONTRACTS = Object.freeze({
|
|
21
|
+
ssoClaims: READABLE_SSO_CLAIMS,
|
|
22
|
+
accountStatus: READABLE_ACCOUNT_STATUS,
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Where a deployment with SSO keeps the current account/binding state that removals and barriers commit to:
|
|
27
|
+
* `account-status` = user-service's status endpoint (combo A); `principal-directory` = permissions-service's own inactive
|
|
28
|
+
* directory links (combo C, no user-service). A direct reader provides immediate cutoff only when its release line lists the
|
|
29
|
+
* source in `currentState` (its checks consult it) and the app declares the reader configured for it.
|
|
30
|
+
*/
|
|
31
|
+
const CURRENT_STATE_SOURCES = Object.freeze(['account-status', 'principal-directory'])
|
|
32
|
+
|
|
33
|
+
/** @type {readonly number[]} */
|
|
34
|
+
const NONE = Object.freeze([])
|
|
35
|
+
/** @type {readonly string[]} */
|
|
36
|
+
const NO_SOURCES = Object.freeze([])
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Supported @saaslayer/permissions release lines, oldest first: from `since`, the formats a release reads, the
|
|
40
|
+
* decision-engine contract it implements, the SSO contracts it reads and the current-state sources its direct checks
|
|
41
|
+
* enforce. Releases older than the first line are retired (unsupported in direct mode). The line starts at 0.1.0; readers
|
|
42
|
+
* of any other package are not comparable and never declarable.
|
|
43
|
+
* @typedef {{ since: string, decisionEngineContract: number, permissionDoc: readonly number[], registrySnapshot: readonly number[],
|
|
44
|
+
* ssoClaims: readonly number[], accountStatus: readonly number[], currentState: readonly string[] }} ReaderLine
|
|
45
|
+
* @type {readonly ReaderLine[]}
|
|
46
|
+
*/
|
|
47
|
+
const READER_RELEASES = Object.freeze([
|
|
48
|
+
Object.freeze({ since: '0.1.0', decisionEngineContract: 2, permissionDoc: READABLE_FORMATS.permissionDoc, registrySnapshot: READABLE_FORMATS.registrySnapshot, ssoClaims: NONE, accountStatus: NONE, currentState: NO_SOURCES }),
|
|
49
|
+
// Reads SSO claims and account-status answers; its direct checks do not consult current state yet (no immediate cutoff).
|
|
50
|
+
Object.freeze({ since: '0.2.0', decisionEngineContract: 2, permissionDoc: READABLE_FORMATS.permissionDoc, registrySnapshot: READABLE_FORMATS.registrySnapshot, ssoClaims: READABLE_CONTRACTS.ssoClaims, accountStatus: READABLE_CONTRACTS.accountStatus, currentState: NO_SOURCES }),
|
|
51
|
+
// Its direct checks ask the configured account-status transport for every SSO session before granting (account-status.js
|
|
52
|
+
// checkSsoStanding): immediate cutoff in A. Local principal-directory barriers (C) are not read by any line yet.
|
|
53
|
+
Object.freeze({ since: '0.3.0', decisionEngineContract: 2, permissionDoc: READABLE_FORMATS.permissionDoc, registrySnapshot: READABLE_FORMATS.registrySnapshot, ssoClaims: READABLE_CONTRACTS.ssoClaims, accountStatus: READABLE_CONTRACTS.accountStatus, currentState: Object.freeze(['account-status']) }),
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* What a release of permissions-service declares about its output, and, with SSO on, where current account state lives.
|
|
58
|
+
* @typedef {{ currentState: 'account-status', accountStatus: number, claims?: number } | { currentState: 'principal-directory' }} SsoRelease
|
|
59
|
+
* account-status (A): the status contract user-service answers and the SSO claim contract it emits; principal-directory (C)
|
|
60
|
+
* @typedef {{ decisionEngineContract: number, writes: { permissionDoc: number, registrySnapshot: number }, sso?: SsoRelease }} WriterRelease
|
|
61
|
+
* @typedef {{ name: string, package: string, version: string, currentState?: string }} DeclaredReader
|
|
62
|
+
* currentState: the current-state source the reader is configured with (e.g. its status endpoint and server key)
|
|
63
|
+
* @typedef {{ readers: DeclaredReader[] }} DirectModeDeclaration the `permissionsDirectMode` block of an app's integration manifest
|
|
64
|
+
* @typedef {'supported'|'newer'|'invalid'} FormatStatus
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/** @param {unknown} v @returns {number[]|null} [major, minor, patch] for a plain `x.y.z` */
|
|
68
|
+
function parseVersion(v) {
|
|
69
|
+
const m = typeof v === 'string' ? /^(\d+)\.(\d+)\.(\d+)$/.exec(v) : null
|
|
70
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** @param {number[]} a @param {number[]} b @returns {number} */
|
|
74
|
+
function compareParsed(a, b) {
|
|
75
|
+
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] - b[i]
|
|
76
|
+
return 0
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The release line a reader version belongs to, or null when it is retired or not a plain `x.y.z`.
|
|
81
|
+
* @param {string} version
|
|
82
|
+
* @param {readonly ReaderLine[]} [releases]
|
|
83
|
+
* @returns {ReaderLine|null}
|
|
84
|
+
*/
|
|
85
|
+
function readerCapability(version, releases = READER_RELEASES) {
|
|
86
|
+
const v = parseVersion(version)
|
|
87
|
+
if (!v) return null
|
|
88
|
+
let line = null
|
|
89
|
+
for (const l of releases) if (compareParsed(v, /** @type {number[]} */ (parseVersion(l.since))) >= 0) line = l
|
|
90
|
+
return line
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** @param {ReaderLine} line @param {SsoRelease} sso */
|
|
94
|
+
function lineReadsSso(line, sso) {
|
|
95
|
+
if (!line.currentState.includes(sso.currentState)) return false
|
|
96
|
+
if (sso.currentState !== 'account-status') return true
|
|
97
|
+
return line.accountStatus.includes(sso.accountStatus) && (sso.claims === undefined || line.ssoClaims.includes(sso.claims))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @param {ReaderLine} line @param {WriterRelease} release */
|
|
101
|
+
const lineReads = (line, release) => line.decisionEngineContract === release.decisionEngineContract
|
|
102
|
+
&& line.permissionDoc.includes(release.writes.permissionDoc)
|
|
103
|
+
&& line.registrySnapshot.includes(release.writes.registrySnapshot)
|
|
104
|
+
&& (!release.sso || lineReadsSso(line, release.sso))
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The first reader release that reads everything a writer release writes, under its decision-engine contract, and with
|
|
108
|
+
* SSO on also reads its claims/status contracts and enforces its current-state source (null = no released reader does;
|
|
109
|
+
* the writer must not ship to an environment with direct readers).
|
|
110
|
+
* @param {WriterRelease} release
|
|
111
|
+
* @param {readonly ReaderLine[]} [releases]
|
|
112
|
+
* @returns {string|null}
|
|
113
|
+
*/
|
|
114
|
+
function minimumReaderFor(release, releases = READER_RELEASES) {
|
|
115
|
+
const line = releases.find((l) => lineReads(l, release))
|
|
116
|
+
return line ? line.since : null
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** @param {unknown} n */
|
|
120
|
+
const isPositiveInt = (n) => Number.isInteger(n) && /** @type {number} */ (n) >= 1
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Whether a release's `sso` block is absent or well formed.
|
|
124
|
+
* @param {unknown} sso
|
|
125
|
+
*/
|
|
126
|
+
function validSso(sso) {
|
|
127
|
+
if (sso === undefined) return true
|
|
128
|
+
if (!sso || typeof sso !== 'object' || Array.isArray(sso)) return false
|
|
129
|
+
const s = /** @type {Record<string, unknown>} */ (sso)
|
|
130
|
+
if (s.currentState === 'principal-directory') return Object.keys(s).length === 1
|
|
131
|
+
if (s.currentState !== 'account-status') return false
|
|
132
|
+
if (Object.keys(s).some((k) => !['currentState', 'accountStatus', 'claims'].includes(k))) return false
|
|
133
|
+
return isPositiveInt(s.accountStatus) && (s.claims === undefined || isPositiveInt(s.claims))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** @param {SsoRelease|undefined} sso */
|
|
137
|
+
const ssoSummary = (sso) => (!sso ? '' : sso.currentState === 'account-status'
|
|
138
|
+
? `, SSO currentState account-status (status contract ${sso.accountStatus}${sso.claims !== undefined ? `, claim contract ${sso.claims}` : ''})`
|
|
139
|
+
: `, SSO currentState ${sso.currentState}`)
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* @param {unknown} raw the stored format field (undefined = 1)
|
|
143
|
+
* @param {readonly number[]} readable
|
|
144
|
+
* @returns {{ format: number|null, status: FormatStatus }}
|
|
145
|
+
*/
|
|
146
|
+
function formatStatus(raw, readable) {
|
|
147
|
+
const format = raw === undefined ? 1 : raw
|
|
148
|
+
if (!Number.isInteger(format) || /** @type {number} */ (format) < 1) return { format: null, status: 'invalid' }
|
|
149
|
+
const n = /** @type {number} */ (format)
|
|
150
|
+
if (readable.includes(n)) return { format: n, status: 'supported' }
|
|
151
|
+
return { format: n, status: n > Math.max(...readable) ? 'newer' : 'invalid' }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** @param {{ schemaVersion?: unknown }} doc a permissions doc */
|
|
155
|
+
const permissionDocFormat = (doc) => formatStatus(doc.schemaVersion, READABLE_FORMATS.permissionDoc)
|
|
156
|
+
|
|
157
|
+
/** @param {{ format?: unknown }} snapshot a registry snapshot */
|
|
158
|
+
const registrySnapshotFormat = (snapshot) => formatStatus(snapshot.format, READABLE_FORMATS.registrySnapshot)
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Upgrade action for a stored format newer than this reader reads.
|
|
162
|
+
* @param {'permissionDoc'|'registrySnapshot'} kind
|
|
163
|
+
* @param {number} format
|
|
164
|
+
* @param {string} installed the reader's own version
|
|
165
|
+
* @returns {string}
|
|
166
|
+
*/
|
|
167
|
+
function upgradeMessage(kind, format, installed) {
|
|
168
|
+
return `${kind} format ${format} is newer than this reader (${READER_PACKAGE} ${installed} reads formats ${READABLE_FORMATS[kind].join(', ')}); upgrade ${READER_PACKAGE} to a release that reads it`
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** @param {unknown} r @returns {r is DeclaredReader} */
|
|
172
|
+
const validReader = (r) => Boolean(r && typeof r === 'object'
|
|
173
|
+
&& typeof (/** @type {any} */ (r)).name === 'string' && (/** @type {any} */ (r)).name.length > 0
|
|
174
|
+
&& (/** @type {any} */ (r)).package === READER_PACKAGE
|
|
175
|
+
&& parseVersion((/** @type {any} */ (r)).version)
|
|
176
|
+
&& ((/** @type {any} */ (r)).currentState === undefined || CURRENT_STATE_SOURCES.includes((/** @type {any} */ (r)).currentState)))
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Preflight a protected update against an app's declared direct-mode readers: every declared reader must read what the
|
|
180
|
+
* release writes. A missing declaration is a prerequisite (never inferred success); an empty `readers` list declares
|
|
181
|
+
* that nothing reads the permissions table directly. With SSO on, a reader must also be at a line whose direct checks
|
|
182
|
+
* enforce the release's current-state source and declare `currentState` (configured for it): a reader that only reads
|
|
183
|
+
* cached permission docs never counts as immediate cutoff.
|
|
184
|
+
* @param {WriterRelease} release
|
|
185
|
+
* @param {DirectModeDeclaration|null|undefined} declaration
|
|
186
|
+
* @param {{ releases?: readonly ReaderLine[] }} [options] releases: the reader lines to check against (default READER_RELEASES)
|
|
187
|
+
* @returns {{ ok: boolean, outcome: 'compatible'|'incompatible'|'declaration_missing'|'declaration_invalid'|'release_invalid', minimumReader: string|null,
|
|
188
|
+
* readers: Array<{ name: string, version: string, ok: boolean, problem?: 'retired'|'below_minimum'|'no_reader_release'|'current_state_unconfigured' }>, actions: string[] }}
|
|
189
|
+
*/
|
|
190
|
+
function preflightDirectReaders(release, declaration, { releases = READER_RELEASES } = {}) {
|
|
191
|
+
if (!validSso(release.sso)) {
|
|
192
|
+
return { ok: false, outcome: 'release_invalid', minimumReader: null, readers: [], actions: [`fix compatibility.permissions.sso: { currentState: 'account-status', accountStatus, claims? } or { currentState: 'principal-directory' }`] }
|
|
193
|
+
}
|
|
194
|
+
const minimumReader = minimumReaderFor(release, releases)
|
|
195
|
+
const sso = release.sso
|
|
196
|
+
if (declaration === undefined || declaration === null) {
|
|
197
|
+
return { ok: false, outcome: 'declaration_missing', minimumReader, readers: [], actions: ['declare permissionsDirectMode.readers in the integration manifest (an empty list when no app reads the permissions table directly)'] }
|
|
198
|
+
}
|
|
199
|
+
const readers = /** @type {any} */ (declaration).readers
|
|
200
|
+
if (!Array.isArray(readers) || !readers.every(validReader)) {
|
|
201
|
+
return { ok: false, outcome: 'declaration_invalid', minimumReader, readers: [], actions: [`fix permissionsDirectMode.readers: each entry needs a name, package '${READER_PACKAGE}' and an exact x.y.z version`] }
|
|
202
|
+
}
|
|
203
|
+
/** @type {string[]} */
|
|
204
|
+
const actions = []
|
|
205
|
+
const results = readers.map((r) => {
|
|
206
|
+
if (!minimumReader) {
|
|
207
|
+
actions.push(`no ${READER_PACKAGE} release reads what this update writes (decision-engine contract ${release.decisionEngineContract}, permissionDoc ${release.writes.permissionDoc}, registrySnapshot ${release.writes.registrySnapshot}${ssoSummary(sso)}); ship a reader first`)
|
|
208
|
+
return { name: r.name, version: r.version, ok: false, problem: /** @type {const} */ ('no_reader_release') }
|
|
209
|
+
}
|
|
210
|
+
if (compareParsed(/** @type {number[]} */ (parseVersion(r.version)), /** @type {number[]} */ (parseVersion(minimumReader))) < 0) {
|
|
211
|
+
actions.push(`upgrade ${r.name} to ${READER_PACKAGE} >=${minimumReader} before this update (readers upgrade before writers)`)
|
|
212
|
+
return { name: r.name, version: r.version, ok: false, problem: readerCapability(r.version, releases) ? /** @type {const} */ ('below_minimum') : /** @type {const} */ ('retired') }
|
|
213
|
+
}
|
|
214
|
+
if (sso && r.currentState !== sso.currentState) {
|
|
215
|
+
actions.push(`configure ${r.name} with the ${sso.currentState} transport and declare currentState: "${sso.currentState}" for it in permissionsDirectMode.readers`)
|
|
216
|
+
return { name: r.name, version: r.version, ok: false, problem: /** @type {const} */ ('current_state_unconfigured') }
|
|
217
|
+
}
|
|
218
|
+
return { name: r.name, version: r.version, ok: true }
|
|
219
|
+
})
|
|
220
|
+
const ok = results.every((r) => r.ok)
|
|
221
|
+
return { ok, outcome: ok ? 'compatible' : 'incompatible', minimumReader, readers: results, actions }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
module.exports = {
|
|
225
|
+
DECISION_ENGINE_CONTRACT,
|
|
226
|
+
READER_PACKAGE,
|
|
227
|
+
READABLE_FORMATS,
|
|
228
|
+
READABLE_CONTRACTS,
|
|
229
|
+
CURRENT_STATE_SOURCES,
|
|
230
|
+
READER_RELEASES,
|
|
231
|
+
readerCapability,
|
|
232
|
+
minimumReaderFor,
|
|
233
|
+
permissionDocFormat,
|
|
234
|
+
registrySnapshotFormat,
|
|
235
|
+
upgradeMessage,
|
|
236
|
+
preflightDirectReaders,
|
|
237
|
+
}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// The SSO claim contract of a verified token (combos A/B): Lite/V1 flat string claims on the ID token, or the Essentials/V2
|
|
2
|
+
// nested `sso` object (ID and access tokens). Both encodings parse to one shape; malformed or newer input and truncated groups fail closed.
|
|
3
|
+
|
|
4
|
+
/** SSO claim contract versions this reader reads. A token without a version marker is contract 1. */
|
|
5
|
+
const READABLE_SSO_CLAIMS = Object.freeze([1])
|
|
6
|
+
|
|
7
|
+
/** Lite/V1 claim names: every value is a string (`sso_groups` a JSON-encoded string array, `sso_groups_truncated` 'true' | 'false'). */
|
|
8
|
+
const FLAT_CLAIMS = Object.freeze({
|
|
9
|
+
connection: 'sso_connection',
|
|
10
|
+
tenant: 'sso_tenant',
|
|
11
|
+
groups: 'sso_groups',
|
|
12
|
+
groupsTruncated: 'sso_groups_truncated',
|
|
13
|
+
version: 'sso_version',
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
/** Essentials/V2 claim: `{ connection, tenant, groups: string[], truncated: boolean, version? }`. */
|
|
17
|
+
const NESTED_CLAIM = 'sso'
|
|
18
|
+
const NESTED_FIELDS = Object.freeze(['connection', 'tenant', 'groups', 'truncated', 'version'])
|
|
19
|
+
|
|
20
|
+
/** @type {readonly string[]} */
|
|
21
|
+
const FLAT_NAMES = Object.freeze(Object.values(FLAT_CLAIMS))
|
|
22
|
+
const FLAT_PREFIX = 'sso_'
|
|
23
|
+
const MAX_ID_LENGTH = 256
|
|
24
|
+
const MAX_GROUP_LENGTH = 256
|
|
25
|
+
const OPAQUE_ID = /^[\x21-\x7e]+$/
|
|
26
|
+
const FLAT_VERSION = /^[1-9]\d*$/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @typedef {Readonly<{ version: number, encoding: 'flat'|'nested', connectionId: string, tenant: string,
|
|
30
|
+
* groups: readonly string[]|null, groupsComplete: boolean }>} SsoClaims
|
|
31
|
+
* groups: the complete group set, or null when the issuer marked it truncated (never a complete empty set)
|
|
32
|
+
* @typedef {{ ok: true, sso: SsoClaims|null }
|
|
33
|
+
* | { ok: false, reason: 'sso_claims_malformed', message: string }
|
|
34
|
+
* | { ok: false, reason: 'sso_claims_newer_than_reader', action: 'upgrade_reader', version: number, message: string }} SsoClaimsRead
|
|
35
|
+
* sso: null for a token without SSO claims (a native or social sign-in)
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
class Malformed extends Error {}
|
|
39
|
+
|
|
40
|
+
/** @param {string} message @returns {never} */
|
|
41
|
+
function malformed(message) {
|
|
42
|
+
throw new Malformed(message)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {unknown} v @returns {v is Record<string, unknown>} */
|
|
46
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
47
|
+
|
|
48
|
+
/** @param {unknown} value @param {string} field @returns {string} */
|
|
49
|
+
function opaqueId(value, field) {
|
|
50
|
+
if (typeof value !== 'string' || value.length > MAX_ID_LENGTH || !OPAQUE_ID.test(value)) malformed(`${field} must be a non-empty id without whitespace (at most ${MAX_ID_LENGTH} characters)`)
|
|
51
|
+
return value
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param {unknown} list @param {string} field @returns {string[]} */
|
|
55
|
+
function groupList(list, field) {
|
|
56
|
+
if (!Array.isArray(list)) malformed(`${field} must be an array of group ids`)
|
|
57
|
+
const seen = new Set()
|
|
58
|
+
for (const g of list) {
|
|
59
|
+
if (typeof g !== 'string' || !g || g.length > MAX_GROUP_LENGTH) malformed(`${field} must hold non-empty group id strings (at most ${MAX_GROUP_LENGTH} characters)`)
|
|
60
|
+
if (seen.has(g)) malformed(`${field} must not repeat a group id`)
|
|
61
|
+
seen.add(g)
|
|
62
|
+
}
|
|
63
|
+
return [...list]
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** @param {Record<string, unknown>} claims @returns {number|null} the flat version marker, null when absent */
|
|
67
|
+
function flatVersion(claims) {
|
|
68
|
+
const raw = claims[FLAT_CLAIMS.version]
|
|
69
|
+
if (raw === undefined) return null
|
|
70
|
+
if (typeof raw !== 'string' || !FLAT_VERSION.test(raw)) malformed(`${FLAT_CLAIMS.version} must be a positive integer string`)
|
|
71
|
+
return Number(raw)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @param {Record<string, unknown>} nested @returns {number|null} */
|
|
75
|
+
function nestedVersion(nested) {
|
|
76
|
+
const raw = nested.version
|
|
77
|
+
if (raw === undefined) return null
|
|
78
|
+
if (!Number.isInteger(raw) || /** @type {number} */ (raw) < 1) malformed(`${NESTED_CLAIM}.version must be a positive integer`)
|
|
79
|
+
return /** @type {number} */ (raw)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* @param {Record<string, unknown>} claims
|
|
84
|
+
* @param {string[]} flatKeys
|
|
85
|
+
* @returns {{ connectionId: string, tenant: string, groups: string[]|null }}
|
|
86
|
+
*/
|
|
87
|
+
function readFlat(claims, flatKeys) {
|
|
88
|
+
const unknown = flatKeys.find((k) => !FLAT_NAMES.includes(k))
|
|
89
|
+
if (unknown) malformed(`${unknown} is not a claim of SSO claim contract 1`)
|
|
90
|
+
for (const name of [FLAT_CLAIMS.connection, FLAT_CLAIMS.tenant, FLAT_CLAIMS.groups, FLAT_CLAIMS.groupsTruncated]) {
|
|
91
|
+
if (typeof claims[name] !== 'string' || !claims[name]) malformed(`${name} is required as a non-empty string`)
|
|
92
|
+
}
|
|
93
|
+
const connectionId = opaqueId(claims[FLAT_CLAIMS.connection], FLAT_CLAIMS.connection)
|
|
94
|
+
const tenant = opaqueId(claims[FLAT_CLAIMS.tenant], FLAT_CLAIMS.tenant)
|
|
95
|
+
const truncated = claims[FLAT_CLAIMS.groupsTruncated]
|
|
96
|
+
if (truncated !== 'true' && truncated !== 'false') malformed(`${FLAT_CLAIMS.groupsTruncated} must be the string "true" or "false"`)
|
|
97
|
+
let parsed
|
|
98
|
+
try {
|
|
99
|
+
parsed = JSON.parse(/** @type {string} */ (claims[FLAT_CLAIMS.groups]))
|
|
100
|
+
} catch {
|
|
101
|
+
malformed(`${FLAT_CLAIMS.groups} must be a JSON-encoded string array`)
|
|
102
|
+
}
|
|
103
|
+
const groups = groupList(parsed, FLAT_CLAIMS.groups)
|
|
104
|
+
return { connectionId, tenant, groups: truncated === 'true' ? null : groups }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @param {unknown} nested
|
|
109
|
+
* @returns {{ connectionId: string, tenant: string, groups: string[]|null }}
|
|
110
|
+
*/
|
|
111
|
+
function readNested(nested) {
|
|
112
|
+
if (!isPlainObject(nested)) return malformed(`${NESTED_CLAIM} must be an object`)
|
|
113
|
+
const unknown = Object.keys(nested).find((k) => !NESTED_FIELDS.includes(k))
|
|
114
|
+
if (unknown) malformed(`${NESTED_CLAIM}.${unknown} is not a field of SSO claim contract 1`)
|
|
115
|
+
if (nested.connection === undefined) malformed(`${NESTED_CLAIM}.connection is required`)
|
|
116
|
+
if (nested.tenant === undefined) malformed(`${NESTED_CLAIM}.tenant is required`)
|
|
117
|
+
const connectionId = opaqueId(nested.connection, `${NESTED_CLAIM}.connection`)
|
|
118
|
+
const tenant = opaqueId(nested.tenant, `${NESTED_CLAIM}.tenant`)
|
|
119
|
+
if (typeof nested.truncated !== 'boolean') malformed(`${NESTED_CLAIM}.truncated must be a boolean`)
|
|
120
|
+
const groups = groupList(nested.groups, `${NESTED_CLAIM}.groups`)
|
|
121
|
+
return { connectionId, tenant, groups: nested.truncated ? null : groups }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* @param {{ groups: string[]|null }} a @param {{ groups: string[]|null }} b
|
|
126
|
+
* @returns {boolean}
|
|
127
|
+
*/
|
|
128
|
+
const sameGroups = (a, b) => (a.groups === null || b.groups === null
|
|
129
|
+
? a.groups === b.groups
|
|
130
|
+
: a.groups.length === b.groups.length && a.groups.every((g) => /** @type {string[]} */ (b.groups).includes(g)))
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Read the SSO claims of an already-verified token payload. A token with neither `sso` nor any `sso_*` claim is not an SSO
|
|
134
|
+
* token (`sso: null`; native behavior is unchanged). Anything else must be a complete, well-typed contract-1 encoding:
|
|
135
|
+
* a partial, mistyped or unknown claim is `sso_claims_malformed`, and a higher version marker is
|
|
136
|
+
* `sso_claims_newer_than_reader`. Truncated groups read as `groups: null` so no caller treats them as a complete (empty) set.
|
|
137
|
+
* Messages name claims, never their values.
|
|
138
|
+
* @param {Record<string, unknown> | null | undefined} claims verified token payload
|
|
139
|
+
* @returns {SsoClaimsRead}
|
|
140
|
+
*/
|
|
141
|
+
function readSsoClaims(claims) {
|
|
142
|
+
if (!claims || typeof claims !== 'object') return { ok: true, sso: null }
|
|
143
|
+
const flatKeys = Object.keys(claims).filter((k) => k.startsWith(FLAT_PREFIX))
|
|
144
|
+
const hasNested = Object.prototype.hasOwnProperty.call(claims, NESTED_CLAIM)
|
|
145
|
+
if (!flatKeys.length && !hasNested) return { ok: true, sso: null }
|
|
146
|
+
try {
|
|
147
|
+
const nested = hasNested ? claims[NESTED_CLAIM] : undefined
|
|
148
|
+
const versions = [flatKeys.length ? flatVersion(claims) : null, hasNested && isPlainObject(nested) ? nestedVersion(nested) : null]
|
|
149
|
+
const declared = versions.filter((v) => v !== null)
|
|
150
|
+
const version = declared.length ? Math.max(.../** @type {number[]} */ (declared)) : 1
|
|
151
|
+
if (!READABLE_SSO_CLAIMS.includes(version)) {
|
|
152
|
+
if (version > Math.max(...READABLE_SSO_CLAIMS)) {
|
|
153
|
+
return { ok: false, reason: 'sso_claims_newer_than_reader', action: 'upgrade_reader', version, message: `SSO claim contract ${version} is newer than this reader (reads ${READABLE_SSO_CLAIMS.join(', ')}); upgrade the reader` }
|
|
154
|
+
}
|
|
155
|
+
malformed(`SSO claim contract ${version} is not readable`)
|
|
156
|
+
}
|
|
157
|
+
if (declared.length === 2 && declared[0] !== declared[1]) malformed('the flat and nested SSO claims disagree on the version')
|
|
158
|
+
const flat = flatKeys.length ? readFlat(claims, flatKeys) : null
|
|
159
|
+
const nestedRead = hasNested ? readNested(nested) : null
|
|
160
|
+
if (flat && nestedRead && (flat.connectionId !== nestedRead.connectionId || flat.tenant !== nestedRead.tenant || !sameGroups(flat, nestedRead))) {
|
|
161
|
+
malformed('the flat and nested SSO claims disagree')
|
|
162
|
+
}
|
|
163
|
+
const read = /** @type {{ connectionId: string, tenant: string, groups: string[]|null }} */ (nestedRead || flat)
|
|
164
|
+
return { ok: true, sso: { version, encoding: nestedRead ? 'nested' : 'flat', connectionId: read.connectionId, tenant: read.tenant, groups: read.groups, groupsComplete: read.groups !== null } }
|
|
165
|
+
} catch (err) {
|
|
166
|
+
if (err instanceof Malformed) return { ok: false, reason: 'sso_claims_malformed', message: err.message }
|
|
167
|
+
throw err
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The Cognito identity provider name prefix user-service gives every SSO connection's provider (`sso-<20 hex>`). */
|
|
172
|
+
const SSO_PROVIDER_PREFIX = 'sso-'
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The provider names a token's Cognito `identities` claim lists (an array, or the JSON string some token paths carry).
|
|
176
|
+
* @param {unknown} identities
|
|
177
|
+
* @returns {string[]}
|
|
178
|
+
*/
|
|
179
|
+
function identityProviders(identities) {
|
|
180
|
+
let list = identities
|
|
181
|
+
if (typeof identities === 'string') {
|
|
182
|
+
try {
|
|
183
|
+
list = JSON.parse(identities)
|
|
184
|
+
} catch {
|
|
185
|
+
return []
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (!Array.isArray(list)) return []
|
|
189
|
+
return list.filter((i) => isPlainObject(i) && typeof i.providerName === 'string').map((i) => /** @type {string} */ (i.providerName))
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Whether a verified token is an SSO session: its `identities` claim names an SSO connection's provider, or it carries any
|
|
194
|
+
* SSO claim (well formed or not, so a malformed one never reads as native). An SSO session's standing is live state that a
|
|
195
|
+
* SaaSLayer permission check asks the account-status transport for; native and social sessions never ask.
|
|
196
|
+
* @param {Record<string, unknown> | null | undefined} claims verified token payload
|
|
197
|
+
* @returns {boolean}
|
|
198
|
+
*/
|
|
199
|
+
function isSsoSession(claims) {
|
|
200
|
+
if (!isPlainObject(claims)) return false
|
|
201
|
+
if (Object.prototype.hasOwnProperty.call(claims, NESTED_CLAIM)) return true
|
|
202
|
+
if (Object.keys(claims).some((k) => k.startsWith(FLAT_PREFIX))) return true
|
|
203
|
+
return identityProviders(claims.identities).some((name) => name.startsWith(SSO_PROVIDER_PREFIX))
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { READABLE_SSO_CLAIMS, FLAT_CLAIMS, NESTED_CLAIM, readSsoClaims, isSsoSession }
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-trigger token contract (E1). Declares, per Cognito CustomMessage triggerSource (+ MagicLink, RegistrationCode, InvitationEmail), the
|
|
3
|
+
* customer-facing {{camelCase}} tokens a template may reference and which are REQUIRED — a customization
|
|
4
|
+
* that would render without a required token is rejected at save (E2) and discarded at render (fail-open).
|
|
5
|
+
* These are the CUSTOMER-facing names (D-g); the runtime supplies their values, the renderer substitutes.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// Brand tokens are available to every trigger (sourced from config.brand + env fallbacks).
|
|
9
|
+
const BRAND_TOKENS = ['companyName', 'productName', 'logoUrl', 'accentColor', 'supportLink', 'supportText']
|
|
10
|
+
|
|
11
|
+
/** @type {Record<string, { required: string[], optional: string[] }>} */
|
|
12
|
+
const TOKEN_REGISTRY = {
|
|
13
|
+
CustomMessage_SignUp: { required: ['ctaUrl'], optional: ['email', 'code'] },
|
|
14
|
+
CustomMessage_ResendCode: { required: ['ctaUrl'], optional: ['email', 'code'] },
|
|
15
|
+
CustomMessage_ForgotPassword: { required: ['ctaUrl'], optional: ['email', 'code'] },
|
|
16
|
+
CustomMessage_AdminCreateUser: { required: ['ctaUrl', 'code'], optional: ['username', 'email'] },
|
|
17
|
+
CustomMessage_UpdateUserAttribute: { required: ['code'], optional: ['ctaUrl'] },
|
|
18
|
+
CustomMessage_VerifyUserAttribute: { required: ['code'], optional: [] },
|
|
19
|
+
MagicLink: { required: ['ctaUrl'], optional: ['email', 'minutes'] },
|
|
20
|
+
RegistrationCode: { required: ['code'], optional: ['email', 'minutes', 'validFor', 'orgName'] },
|
|
21
|
+
InvitationEmail: { required: ['ctaUrl', 'orgName', 'email', 'expiresAt'], optional: ['inviterName', 'headline'] },
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** All trigger keys this registry covers. */
|
|
25
|
+
const TRIGGERS = Object.keys(TOKEN_REGISTRY)
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Required token names for a trigger (empty array for an unknown trigger).
|
|
29
|
+
* @param {string} triggerSource
|
|
30
|
+
* @returns {string[]}
|
|
31
|
+
*/
|
|
32
|
+
function getRequiredTokens(triggerSource) {
|
|
33
|
+
const entry = TOKEN_REGISTRY[triggerSource]
|
|
34
|
+
return entry ? entry.required.slice() : []
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Every token (brand + trigger-specific required/optional) a customer may reference for a trigger.
|
|
39
|
+
* @param {string} triggerSource
|
|
40
|
+
* @returns {string[]}
|
|
41
|
+
*/
|
|
42
|
+
function listTokens(triggerSource) {
|
|
43
|
+
const entry = TOKEN_REGISTRY[triggerSource]
|
|
44
|
+
if (!entry) return BRAND_TOKENS.slice()
|
|
45
|
+
return Array.from(new Set([...entry.required, ...entry.optional, ...BRAND_TOKENS]))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
module.exports = { TOKEN_REGISTRY, BRAND_TOKENS, TRIGGERS, getRequiredTokens, listTokens }
|