saaslayer 0.4.2 → 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.
Files changed (49) hide show
  1. package/package.json +5 -6
  2. package/src/commands/operations.js +1 -1
  3. package/src/commands/users-management.js +2 -2
  4. package/src/users-import/ids.js +1 -1
  5. package/vendor/config/login-domain.js +213 -0
  6. package/vendor/discovery/index.d.mts +109 -0
  7. package/vendor/discovery/index.mjs +409 -0
  8. package/vendor/ids/index.d.ts +21 -0
  9. package/vendor/ids/index.js +237 -0
  10. package/vendor/migrations/backups.js +118 -0
  11. package/vendor/migrations/child.js +78 -0
  12. package/vendor/migrations/credentials.js +103 -0
  13. package/vendor/migrations/errors.js +30 -0
  14. package/vendor/migrations/exec-child.js +78 -0
  15. package/vendor/migrations/gate.js +51 -0
  16. package/vendor/migrations/index.js +30 -0
  17. package/vendor/migrations/inventory.js +92 -0
  18. package/vendor/migrations/log.js +14 -0
  19. package/vendor/migrations/release.js +45 -0
  20. package/vendor/migrations/report.js +129 -0
  21. package/vendor/migrations/rules.js +104 -0
  22. package/vendor/migrations/run.js +311 -0
  23. package/vendor/migrations/session-policy.js +37 -0
  24. package/vendor/migrations/step-guard.js +82 -0
  25. package/vendor/operations/activity.d.ts +21 -0
  26. package/vendor/operations/activity.js +126 -0
  27. package/vendor/operations/index.d.ts +60 -0
  28. package/vendor/operations/index.js +471 -0
  29. package/vendor/permissions-engine-core/account-status.js +270 -0
  30. package/vendor/permissions-engine-core/delegation.js +174 -0
  31. package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
  32. package/vendor/permissions-engine-core/sso-claims.js +206 -0
  33. package/vendor/user-management/cognito/emails/token-registry.js +48 -0
  34. package/vendor/user-management/email/validate.js +207 -0
  35. package/vendor/user-management/extensibility/hook-contract.js +720 -0
  36. package/vendor/user-management/extensibility/safe-webhook.js +85 -0
  37. package/vendor/user-management/identity/admission.js +215 -0
  38. package/vendor/user-management/identity/attr.js +27 -0
  39. package/vendor/user-management/identity/attribute-registry.js +115 -0
  40. package/vendor/user-management/identity/email.js +25 -0
  41. package/vendor/user-management/identity/ensure-suid.js +74 -0
  42. package/vendor/user-management/identity/pointers.js +192 -0
  43. package/vendor/user-management/identity/stitch-provider.js +275 -0
  44. package/vendor/user-management/management/apply-request.js +227 -0
  45. package/vendor/user-management/management/core-profile.js +110 -0
  46. package/vendor/user-management/management/index.js +23 -0
  47. package/vendor/user-management/management/purposes.js +94 -0
  48. package/vendor/user-management/management/registry.js +569 -0
  49. package/vendor/user-management/store/table.js +332 -0
@@ -0,0 +1,85 @@
1
+ // SSRF guards for hook HTTPS targets: https only, no internal hosts, and a DNS lookup that re-validates the address
2
+ // the TCP connection is pinned to, so a rebinding hostname can't swap in an internal one.
3
+ const dns = require('dns')
4
+ const net = require('net')
5
+
6
+ const BLOCKED_HOSTNAMES = ['localhost', 'metadata.google.internal']
7
+
8
+ /**
9
+ * Whether an IP literal is publicly routable (not loopback / private / link-local / CGNAT / unspecified /
10
+ * unique-local, including IPv4-mapped IPv6 forms of those).
11
+ * @param {string} ip
12
+ * @returns {boolean}
13
+ */
14
+ function isPublicAddress(ip) {
15
+ const v = net.isIP(ip)
16
+ if (v === 4) {
17
+ const [a, b] = ip.split('.').map(Number)
18
+ if (a === 0 || a === 10 || a === 127) return false
19
+ if (a === 169 && b === 254) return false
20
+ if (a === 172 && b >= 16 && b <= 31) return false
21
+ if (a === 192 && b === 168) return false
22
+ if (a === 100 && b >= 64 && b <= 127) return false
23
+ if (a >= 224) return false
24
+ return true
25
+ }
26
+ if (v === 6) {
27
+ const lower = ip.toLowerCase()
28
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower)
29
+ if (mapped) return isPublicAddress(mapped[1])
30
+ // WHATWG URL serializes IPv4-mapped addresses in hex (::ffff:a00:1 == ::ffff:10.0.0.1).
31
+ const mappedHex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(lower)
32
+ if (mappedHex) {
33
+ const hi = parseInt(mappedHex[1], 16)
34
+ const lo = parseInt(mappedHex[2], 16)
35
+ return isPublicAddress(`${hi >> 8}.${hi & 255}.${lo >> 8}.${lo & 255}`)
36
+ }
37
+ if (lower === '::' || lower === '::1') return false
38
+ if (/^fe[89ab]/.test(lower)) return false // link-local fe80::/10
39
+ if (/^f[cd]/.test(lower)) return false // unique-local fc00::/7
40
+ if (/^ff/.test(lower)) return false // multicast
41
+ return true
42
+ }
43
+ return false
44
+ }
45
+
46
+ /**
47
+ * Throw unless `url` is an https URL without credentials whose host is not an internal name or address.
48
+ * @param {string} url
49
+ * @returns {URL}
50
+ */
51
+ function assertSafeWebhookUrl(url) {
52
+ let u
53
+ try { u = new URL(url) } catch { throw new Error('webhook URL is invalid') }
54
+ if (u.protocol !== 'https:') throw new Error('webhook URL must be https')
55
+ if (u.username || u.password) throw new Error('webhook URL must not carry credentials')
56
+ const host = u.hostname.replace(/^\[|\]$/g, '').toLowerCase()
57
+ if (BLOCKED_HOSTNAMES.includes(host) || host.endsWith('.localhost') || host.endsWith('.internal')) {
58
+ throw new Error('webhook URL host is internal')
59
+ }
60
+ if (net.isIP(host) && !isPublicAddress(host)) throw new Error('webhook URL host is an internal address')
61
+ return u
62
+ }
63
+
64
+ /**
65
+ * Wrap a dns.lookup-compatible resolver so every resolved address must be public; used as the https
66
+ * `lookup` so the socket connects only to the address that passed the check.
67
+ * @param {typeof dns.lookup} [resolve]
68
+ * @returns {(hostname: string, options: any, cb: Function) => void}
69
+ */
70
+ function createSafeLookup(resolve = dns.lookup) {
71
+ return (hostname, options, cb) => {
72
+ const opts = typeof options === 'object' && options ? options : {}
73
+ resolve(hostname, { ...opts, all: true }, (err, addrs) => {
74
+ if (err) return cb(err)
75
+ const list = Array.isArray(addrs) ? addrs : [{ address: addrs, family: net.isIP(addrs) }]
76
+ if (!list.length || list.some((a) => !isPublicAddress(a.address))) {
77
+ return cb(new Error(`webhook host ${hostname} resolves to an internal address`))
78
+ }
79
+ if (opts.all) return cb(null, list)
80
+ return cb(null, list[0].address, list[0].family)
81
+ })
82
+ }
83
+ }
84
+
85
+ module.exports = { isPublicAddress, assertSafeWebhookUrl, createSafeLookup }
@@ -0,0 +1,215 @@
1
+ // The creation journal and account admission. The journal (ADMISSION#<userPoolId>#<sub> / JOURNAL) picks the one
2
+ // canonical suid for a Cognito user with a conditional put, before custom:suid is written, so concurrent minters converge.
3
+ // The admission (USER#<suid> / ADMISSION) records once that an account's creation reached a known onboarding outcome,
4
+ // and in the same transaction writes the account's one immutable creation event (HOOKEVT#<suid> / user.created) and
5
+ // marks it unpublished (HOOKEVT#pending / <occurredAt>#<suid>).
6
+ const { GetCommand, UpdateCommand, TransactWriteCommand } = require('@aws-sdk/lib-dynamodb')
7
+ const { keys, ITEM } = require('../store/table')
8
+ const { newHookEventId, EVENT_TYPES } = require('../extensibility/hook-contract')
9
+
10
+ const CREATED_EVENT = EVENT_TYPES.afterUserCreated
11
+
12
+ /** The onboarding outcomes that admit an account: its personal org exists, or the deployment gives it none. */
13
+ const ONBOARDING_OUTCOMES = ['personalOwner', 'none']
14
+
15
+ /** @typedef {'pending'|'admitted'|'cancelled'} AdmissionState */
16
+
17
+ /** @param {unknown} err */
18
+ const conditionFailed = (err) => !!err && /** @type {{ name?: string }} */ (err).name === 'ConditionalCheckFailedException'
19
+
20
+ /**
21
+ * @param {{ doc: { send: Function }, tableName: string, now?: () => string }} deps `now` returns an ISO timestamp
22
+ */
23
+ function createAdmissions({ doc, tableName, now = () => new Date().toISOString() }) {
24
+ /**
25
+ * The creation journal row of a Cognito user, or null. Strongly consistent.
26
+ * @param {{ userPoolId: string, sub: string }} credential
27
+ * @returns {Promise<Record<string, any>|null>}
28
+ */
29
+ async function journalFor({ userPoolId, sub }) {
30
+ const res = await doc.send(new GetCommand({ TableName: tableName, Key: keys.admissionJournal(userPoolId, sub), ConsistentRead: true }))
31
+ return (res && res.Item) || null
32
+ }
33
+
34
+ /**
35
+ * Choose the canonical suid of a Cognito user: the first caller's minted id is recorded and every later caller gets
36
+ * that one. Throws when the journal cannot be written or read, so no caller proceeds with an id that may not be it.
37
+ * @param {{ userPoolId: string, sub: string, mint: () => string, via: string }} input `via` names the caller that claimed
38
+ * @returns {Promise<{ suid: string, claimed: boolean }>} claimed = this call recorded the suid
39
+ */
40
+ async function claimSuid({ userPoolId, sub, mint, via }) {
41
+ const suid = userPoolId && sub ? mint() : ''
42
+ if (!suid) throw new Error('claimSuid: userPoolId, sub and a minted suid are required')
43
+ try {
44
+ await doc.send(new UpdateCommand({
45
+ TableName: tableName,
46
+ Key: keys.admissionJournal(userPoolId, sub),
47
+ UpdateExpression: 'SET itemType = :itemType, suid = :suid, via = :via, createdAt = :at',
48
+ ConditionExpression: 'attribute_not_exists(pk)',
49
+ ExpressionAttributeValues: { ':itemType': ITEM.ADMISSION_JOURNAL, ':suid': suid, ':via': via, ':at': now() },
50
+ }))
51
+ return { suid, claimed: true }
52
+ } catch (err) {
53
+ if (!conditionFailed(err)) throw err
54
+ }
55
+ const journal = await journalFor({ userPoolId, sub })
56
+ if (!journal || !journal.suid) throw new Error('claimSuid: the creation journal has no suid for this credential')
57
+ return { suid: journal.suid, claimed: false }
58
+ }
59
+
60
+ /**
61
+ * The account's admission row, or null. Strongly consistent.
62
+ * @param {string} suid
63
+ * @returns {Promise<Record<string, any>|null>}
64
+ */
65
+ async function get(suid) {
66
+ const res = await doc.send(new GetCommand({ TableName: tableName, Key: keys.userAdmission(suid), ConsistentRead: true }))
67
+ return (res && res.Item) || null
68
+ }
69
+
70
+ /**
71
+ * The state an admission is in after a refused conditional write.
72
+ * @param {string} suid
73
+ * @returns {Promise<AdmissionState|null>}
74
+ */
75
+ async function stateOf(suid) {
76
+ const row = await get(suid)
77
+ return row ? row.state : null
78
+ }
79
+
80
+ /**
81
+ * Record that the account exists but its onboarding outcome is not known. Create-once: an account that already has an
82
+ * admission keeps it.
83
+ * @param {{ suid: string, via: string }} input
84
+ * @returns {Promise<{ state: AdmissionState|null }>} the state the account is in
85
+ */
86
+ async function markPending({ suid, via }) {
87
+ const at = now()
88
+ try {
89
+ await doc.send(new UpdateCommand({
90
+ TableName: tableName,
91
+ Key: keys.userAdmission(suid),
92
+ UpdateExpression: 'SET itemType = :itemType, suid = :suid, #state = :pending, via = :via, pendingAt = :at, updatedAt = :at',
93
+ ConditionExpression: 'attribute_not_exists(pk)',
94
+ ExpressionAttributeNames: { '#state': 'state' },
95
+ ExpressionAttributeValues: { ':itemType': ITEM.ADMISSION, ':suid': suid, ':pending': 'pending', ':via': via, ':at': at },
96
+ }))
97
+ return { state: 'pending' }
98
+ } catch (err) {
99
+ if (!conditionFailed(err)) throw err
100
+ }
101
+ return { state: await stateOf(suid) }
102
+ }
103
+
104
+ /**
105
+ * The admission update of one account: pending or absent becomes admitted.
106
+ * @param {{ suid: string, onboarding: string, via: string, at: string }} input
107
+ */
108
+ const admissionUpdate = ({ suid, onboarding, via, at }) => ({
109
+ TableName: tableName,
110
+ Key: keys.userAdmission(suid),
111
+ UpdateExpression: 'SET itemType = :itemType, suid = :suid, #state = :admitted, onboarding = :onboarding, admittedAt = :at, updatedAt = :at, via = if_not_exists(via, :via)',
112
+ ConditionExpression: 'attribute_not_exists(pk) OR #state = :pending',
113
+ ExpressionAttributeNames: { '#state': 'state' },
114
+ ExpressionAttributeValues: { ':itemType': ITEM.ADMISSION, ':suid': suid, ':admitted': 'admitted', ':pending': 'pending', ':onboarding': onboarding, ':at': at, ':via': via },
115
+ })
116
+
117
+ /**
118
+ * The runtime config version current now: the creation event is pinned to it, so the event is handled under the
119
+ * hooks configured when the account was admitted. Strongly consistent; a failed read fails the admit.
120
+ * @returns {Promise<number>}
121
+ */
122
+ async function currentConfigVersion() {
123
+ const res = await doc.send(new GetCommand({ TableName: tableName, Key: keys.configCurrent(), ConsistentRead: true }))
124
+ return (res && res.Item && res.Item.version) || 0
125
+ }
126
+
127
+ /**
128
+ * Admit the account: its creation reached the onboarding outcome `onboarding`. Happens once; an account already
129
+ * admitted stays as it was and a cancelled one stays cancelled. The same transaction creates the account's creation
130
+ * event (a reference: id, type, pinned config version; no contact data), so an admitted account has exactly one and
131
+ * an account that is not admitted has none.
132
+ * @param {{ suid: string, onboarding: 'personalOwner'|'none', via: string }} input
133
+ * @returns {Promise<{ state: AdmissionState|null, admitted: boolean, eventId?: string }>} admitted = this call admitted
134
+ * the account; eventId = the creation event this call wrote
135
+ */
136
+ async function admit({ suid, onboarding, via }) {
137
+ if (!ONBOARDING_OUTCOMES.includes(onboarding)) throw new Error('admit: onboarding must be personalOwner or none')
138
+ const configVersion = await currentConfigVersion()
139
+ const at = now()
140
+ const eventId = newHookEventId()
141
+ const admission = admissionUpdate({ suid, onboarding, via, at })
142
+ try {
143
+ await doc.send(new TransactWriteCommand({
144
+ TransactItems: [
145
+ { Update: admission },
146
+ {
147
+ Update: {
148
+ TableName: tableName,
149
+ Key: keys.hookEvent(suid, CREATED_EVENT),
150
+ UpdateExpression: 'SET itemType = :itemType, id = :id, #type = :type, suid = :suid, occurredAt = :at, via = :via, onboarding = :onboarding, configVersion = :configVersion, #status = :pending',
151
+ ConditionExpression: 'attribute_not_exists(pk)',
152
+ ExpressionAttributeNames: { '#type': 'type', '#status': 'status' },
153
+ ExpressionAttributeValues: { ':itemType': ITEM.HOOK_EVENT, ':id': eventId, ':type': CREATED_EVENT, ':suid': suid, ':at': at, ':via': via, ':onboarding': onboarding, ':configVersion': configVersion, ':pending': 'pending' },
154
+ },
155
+ },
156
+ // Unpublished until the publisher confirms it on the hooks queue; the reconcile sweep publishes what is left.
157
+ {
158
+ Update: {
159
+ TableName: tableName,
160
+ Key: keys.hookEventPending(at, suid),
161
+ UpdateExpression: 'SET suid = :suid, occurredAt = :at',
162
+ ConditionExpression: 'attribute_not_exists(pk)',
163
+ ExpressionAttributeValues: { ':suid': suid, ':at': at },
164
+ },
165
+ },
166
+ ],
167
+ }))
168
+ return { state: 'admitted', admitted: true, eventId }
169
+ } catch (err) {
170
+ if (!err || /** @type {{ name?: string }} */ (err).name !== 'TransactionCanceledException') throw err
171
+ const reasons = /** @type {{ CancellationReasons?: Array<{ Code?: string }> }} */ (err).CancellationReasons || []
172
+ const refused = (/** @type {number} */ i) => !!reasons[i] && reasons[i].Code === 'ConditionalCheckFailed'
173
+ // Cancelled for another reason (a concurrent transaction on these rows, throttling): not an answer.
174
+ if (!refused(0) && !refused(1)) throw err
175
+ // The account can be admitted but its creation event already exists: admit it and keep that event.
176
+ if (!refused(0)) {
177
+ try {
178
+ await doc.send(new UpdateCommand(admission))
179
+ return { state: 'admitted', admitted: true }
180
+ } catch (updateErr) {
181
+ if (!conditionFailed(updateErr)) throw updateErr
182
+ }
183
+ }
184
+ }
185
+ return { state: await stateOf(suid), admitted: false }
186
+ }
187
+
188
+ /**
189
+ * Cancel the account's admission (the account was deleted). The row stays as a marker, so nothing admits it again.
190
+ * An account with no admission gets none.
191
+ * @param {string} suid
192
+ * @returns {Promise<{ state: 'cancelled'|null }>}
193
+ */
194
+ async function cancel(suid) {
195
+ const at = now()
196
+ try {
197
+ await doc.send(new UpdateCommand({
198
+ TableName: tableName,
199
+ Key: keys.userAdmission(suid),
200
+ UpdateExpression: 'SET #state = :cancelled, cancelledAt = if_not_exists(cancelledAt, :at), updatedAt = :at',
201
+ ConditionExpression: 'attribute_exists(pk)',
202
+ ExpressionAttributeNames: { '#state': 'state' },
203
+ ExpressionAttributeValues: { ':cancelled': 'cancelled', ':at': at },
204
+ }))
205
+ return { state: 'cancelled' }
206
+ } catch (err) {
207
+ if (!conditionFailed(err)) throw err
208
+ }
209
+ return { state: null }
210
+ }
211
+
212
+ return { claimSuid, journalFor, markPending, admit, cancel, get }
213
+ }
214
+
215
+ module.exports = { createAdmissions, ONBOARDING_OUTCOMES }
@@ -0,0 +1,27 @@
1
+ // Shared Cognito attribute-value predicates. Cognito delivers user attributes as STRINGS in trigger
2
+ // events (email_verified arrives as the string "true", never boolean true), so truthiness must accept both.
3
+
4
+ /**
5
+ * Is a Cognito attribute value truthy? Accepts the string "true" (the trigger-event shape) OR boolean true.
6
+ * Everything else (undefined, "", "false", false) is falsy. This is the single source of truth reused by
7
+ * PostConfirmation (email_verified provenance) and PreSignUp (external-provider verified-email guard).
8
+ * @param {unknown} v
9
+ * @returns {boolean}
10
+ */
11
+ function isTruthyAttr(v) {
12
+ return v === 'true' || v === true
13
+ }
14
+
15
+ /**
16
+ * Read one attribute value off a Cognito [{Name,Value}] attribute list (ListUsers `Attributes`,
17
+ * AdminGetUser `UserAttributes`). A missing list or attribute yields undefined.
18
+ * @param {Array<{ Name?: string, Value?: string }>|undefined} attributes
19
+ * @param {string} name
20
+ * @returns {string|undefined}
21
+ */
22
+ function attributeValue(attributes, name) {
23
+ const found = (attributes || []).find((a) => a.Name === name)
24
+ return found ? found.Value : undefined
25
+ }
26
+
27
+ module.exports = { isTruthyAttr, attributeValue }
@@ -0,0 +1,115 @@
1
+ // Attribute-ownership registry (bead monorepo-2gxc6.1): the SINGLE source of truth for how every Cognito
2
+ // user attribute / JWT claim is governed — who may write it (server vs client), whether it may appear in a
3
+ // token, and whether it is a RESERVED SaaSLayer/issuer claim that config/hooks may never emit. Consolidates
4
+ // what was previously divergent across stack.yml (Read/WriteAttributes), claim-mappings.js (PROTECTED_CLAIMS)
5
+ // and hooks.js (PROTECTED_HOOK_ATTRS) so there is exactly one answer.
6
+
7
+ // owner: 'server' = server-owned (client-write-denied); 'client' = client-writable; 'issuer' = issuer-owned
8
+ // (Cognito/JWT sets it; we must never override it). inToken: whether it is stamped into the ID token.
9
+ // reserved: config/hooks may NEVER emit it (identity/authz/impersonation-escalation surface).
10
+ // tokenOnly: a claim no Cognito attribute holds (never a claim-mapping source).
11
+ const ATTRIBUTES = {
12
+ // --- SaaSLayer canonical identity claims (server-owned, in token, reserved) ---
13
+ 'custom:suid': { owner: 'server', inToken: true, reserved: true },
14
+ 'custom:soid': { owner: 'server', inToken: true, reserved: true }, // NEW — semantic successor of custom:orgId
15
+ 'custom:orgId': { owner: 'server', inToken: true, reserved: true }, // legacy; reserved-forever so no hook/config ever re-emits it (green pools drop the schema attr, keep the guard)
16
+ // --- impersonation set (server-owned, in token, reserved — rbac trusts custom:as_suid) ---
17
+ 'custom:as_suid': { owner: 'server', inToken: true, reserved: true },
18
+ 'custom:as_org': { owner: 'server', inToken: true, reserved: true },
19
+ 'custom:as_email': { owner: 'server', inToken: true, reserved: true },
20
+ 'custom:as_exp': { owner: 'server', inToken: true, reserved: true },
21
+ 'custom:as_mode': { owner: 'server', inToken: true, reserved: true },
22
+ // --- MFA status stamped by PreTokenGeneration (server-owned, in token, reserved — the API MFA gate trusts it) ---
23
+ 'custom:mfa': { owner: 'server', inToken: true, reserved: true },
24
+ 'custom:mfa_exp': { owner: 'server', inToken: true, reserved: true },
25
+ // --- opted-in login state stamped by PreTokenGeneration's issuance gate (identity-pool rules and the API gate trust it) ---
26
+ 'custom:login_state': { owner: 'server', inToken: true, reserved: true },
27
+ // --- opted-in account security version stamped by the same gate (the API denies a token minted before a revocation) ---
28
+ 'custom:sv': { owner: 'server', inToken: true, reserved: true },
29
+ // --- opted-in MFA enrollment time stamped by the same gate (downstream consumers compare the token's auth_time to it) ---
30
+ 'custom:mfa_enrolled_at': { owner: 'server', inToken: true, reserved: true },
31
+ // --- SSO claims stamped by PreTokenGeneration from durable connection and group state (src/sso/sso-claims.js). Token-only:
32
+ // no Cognito attribute holds them, so none is a mapping source. Flat strings in the ID token (Lite/V1); `sso` is the
33
+ // nested object a V2 trigger adds to the ID and access tokens. ---
34
+ 'sso_connection': { owner: 'server', inToken: true, reserved: true, tokenOnly: true },
35
+ 'sso_tenant': { owner: 'server', inToken: true, reserved: true, tokenOnly: true },
36
+ 'sso_groups': { owner: 'server', inToken: true, reserved: true, tokenOnly: true },
37
+ 'sso_groups_truncated': { owner: 'server', inToken: true, reserved: true, tokenOnly: true },
38
+ 'sso': { owner: 'server', inToken: true, reserved: true, tokenOnly: true },
39
+ // --- issuer-owned / non-overridable standard claims (reserved) ---
40
+ 'sub': { owner: 'issuer', inToken: true, reserved: true },
41
+ // email: issuer claim, but the ATTRIBUTE is client-writable (app-client WriteAttributes; verify-before-update).
42
+ 'email': { owner: 'issuer', inToken: true, reserved: true, clientWrite: true },
43
+ 'aud': { owner: 'issuer', inToken: true, reserved: true },
44
+ 'iss': { owner: 'issuer', inToken: true, reserved: true },
45
+ 'exp': { owner: 'issuer', inToken: true, reserved: true },
46
+ 'iat': { owner: 'issuer', inToken: true, reserved: true },
47
+ 'token_use': { owner: 'issuer', inToken: true, reserved: true },
48
+ 'auth_time': { owner: 'issuer', inToken: true, reserved: true },
49
+ 'amr': { owner: 'issuer', inToken: true, reserved: true },
50
+ 'cognito:amr': { owner: 'issuer', inToken: true, reserved: true },
51
+ 'cognito:groups': { owner: 'issuer', inToken: true, reserved: true },
52
+ // --- user-controlled standard profile attributes (app-client WriteAttributes and/or PATCH /api/me) ---
53
+ 'name': { owner: 'client', inToken: true, reserved: false },
54
+ 'given_name': { owner: 'client', inToken: true, reserved: false },
55
+ 'family_name': { owner: 'client', inToken: true, reserved: false },
56
+ 'locale': { owner: 'client', inToken: false, reserved: false },
57
+ 'zoneinfo': { owner: 'client', inToken: false, reserved: false },
58
+ 'picture': { owner: 'client', inToken: false, reserved: false },
59
+ // --- client-writable, consumed SERVER-SIDE, NOT token claims ---
60
+ 'custom:auid': { owner: 'client', inToken: false, reserved: false }, // anonymous analytics id
61
+ 'custom:redirect': { owner: 'client', inToken: false, reserved: false }, // post-verify return URL (client-set, origin-allowlisted, ephemeral)
62
+ // --- server-owned backend stores (never a raw token claim; both are permitted claim-mapping sources) ---
63
+ 'custom:publicMeta': { owner: 'server', inToken: false, reserved: false }, // public store: user-readable, server-written
64
+ 'custom:privateMeta': { owner: 'server', inToken: false, reserved: false, developerOnly: true }, // dev-only store: hidden from the user
65
+ }
66
+
67
+ /** The canonical RESERVED claim UNION — config/hooks may never emit any member. Basis for the I4 guard. */
68
+ const RESERVED_CLAIMS = new Set(Object.keys(ATTRIBUTES).filter((k) => ATTRIBUTES[k].reserved))
69
+
70
+ /** @param {string} name @returns {boolean} true if config/hooks may never emit this claim name. */
71
+ function isReserved(name) { return RESERVED_CLAIMS.has(name) }
72
+
73
+ /** @param {string} attr @returns {boolean} true if only the server may write this attribute. */
74
+ function isServerOwned(attr) { return ATTRIBUTES[attr] ? ATTRIBUTES[attr].owner !== 'client' : false }
75
+
76
+ /** @param {string} attr @returns {boolean} true if a client may write this attribute. */
77
+ function isClientWritable(attr) { return ATTRIBUTES[attr] ? ATTRIBUTES[attr].owner === 'client' || ATTRIBUTES[attr].clientWrite === true : false }
78
+
79
+ /**
80
+ * DENY-BY-DEFAULT source check for claim mappings: only a REGISTERED, server-owned attribute that no client
81
+ * can write may be copied into a token claim. Unknown / client-writable / issuer attributes are refused, so a
82
+ * user can never self-mint a claim by editing their own profile.
83
+ * @param {string} attr @returns {boolean}
84
+ */
85
+ function isMappableSource(attr) {
86
+ const a = ATTRIBUTES[attr]
87
+ return !!a && a.owner === 'server' && !a.tokenOnly && !isClientWritable(attr)
88
+ }
89
+
90
+ /** The client-writable CUSTOM attribute allowlist (app-client WriteAttributes should match this for custom:* attrs). */
91
+ function clientWritableAttrs() { return Object.keys(ATTRIBUTES).filter((k) => k.startsWith('custom:') && isClientWritable(k)) }
92
+
93
+ /** Attributes that are token-eligible AND NOT client-writable — the minimal ReadAttributes an app client
94
+ * needs for identity (bead I0a restricts ReadAttributes to exclude client-writable buckets like custom:auid/redirect). */
95
+ function tokenReadableServerAttrs() {
96
+ return Object.keys(ATTRIBUTES).filter((k) => ATTRIBUTES[k].inToken && ATTRIBUTES[k].owner !== 'client' && k.startsWith('custom:'))
97
+ }
98
+
99
+ /** The standard (non-custom) client-owned profile attributes: what an administrator may update on a user (matrix U5);
100
+ * identity, verification and custom:* attributes are reserved fields (U6). */
101
+ function profileAttributes() {
102
+ return Object.keys(ATTRIBUTES).filter((k) => ATTRIBUTES[k].owner === 'client' && !k.startsWith('custom:'))
103
+ }
104
+
105
+ module.exports = {
106
+ ATTRIBUTES,
107
+ profileAttributes,
108
+ RESERVED_CLAIMS,
109
+ isReserved,
110
+ isServerOwned,
111
+ isClientWritable,
112
+ isMappableSource,
113
+ clientWritableAttrs,
114
+ tokenReadableServerAttrs,
115
+ }
@@ -0,0 +1,25 @@
1
+ // Email normalization shared by every user-service email write and lookup.
2
+ // Emails are stored and compared lowercased + trimmed, so one address never splits into case variants.
3
+
4
+ /**
5
+ * @param {unknown} email
6
+ * @returns {string} trimmed, lowercased email ('' when absent)
7
+ */
8
+ function normalizeEmail(email) {
9
+ return String(email || '').trim().toLowerCase()
10
+ }
11
+
12
+ /**
13
+ * The domain of an email address: the trimmed, lower-case part after its last @ (the PROFILE's emailDomain, the
14
+ * email-domain-index key, and the SSO domain a claim names).
15
+ * @param {unknown} email
16
+ * @returns {string|null} null when there is no domain
17
+ */
18
+ function emailDomain(email) {
19
+ if (typeof email !== 'string') return null
20
+ const at = email.lastIndexOf('@')
21
+ const domain = at > 0 ? email.slice(at + 1).trim().toLowerCase() : ''
22
+ return domain || null
23
+ }
24
+
25
+ module.exports = { normalizeEmail, emailDomain }
@@ -0,0 +1,74 @@
1
+ // ensureSuid (M0.2): idempotently give a Cognito user a stable, server-owned SaaSLayer user id
2
+ // (custom:suid). Mints a ULID-style id if absent and writes it via AdminUpdateUserAttributes;
3
+ // NEVER overwrites an existing value (write-once). Called at user-creation time (PostConfirmation +
4
+ // seed). The custom:suid attribute is mutable-in-schema but client-write-denied, so only the server
5
+ // (this module) ever sets it — the immutable-once-set guarantee behind the D27 stable-identity contract.
6
+
7
+ const { AdminUpdateUserAttributesCommand, AdminGetUserCommand } = require('@aws-sdk/client-cognito-identity-provider')
8
+ // One id generator for the platform (@saaslayer/ids, a port of @revenue-engine/typeid). newId() = a BARE
9
+ // 26-char monotonic-UUIDv7 body (no user_ prefix) — the field it lives in (custom:suid / rbac USER#) says user.
10
+ const { generateTypeIdSuffix: newId } = require('../../ids')
11
+
12
+ /**
13
+ * Read a Cognito attribute value. Handles both shapes Cognito uses: the [{Name,Value}] list
14
+ * (AdminGetUser / AdminUpdateUserAttributes) and the flat map that Lambda trigger events deliver
15
+ * (event.request.userAttributes = { 'custom:suid': '...' }). Returns null for absent/empty.
16
+ */
17
+ function getAttr(attributes, name) {
18
+ if (Array.isArray(attributes)) {
19
+ const found = attributes.find((a) => a && a.Name === name)
20
+ return found && typeof found.Value === 'string' && found.Value.length > 0 ? found.Value : null
21
+ }
22
+ if (attributes && typeof attributes === 'object') {
23
+ const v = attributes[name]
24
+ return typeof v === 'string' && v.length > 0 ? v : null
25
+ }
26
+ return null
27
+ }
28
+
29
+ /**
30
+ * Ensure a user has a stable custom:suid. Idempotent + write-once.
31
+ * @param {Object} input
32
+ * @param {Object} input.cognito CognitoIdentityProvider client (has .send)
33
+ * @param {string} input.userPoolId
34
+ * @param {string} input.username
35
+ * @param {Array<{Name:string,Value:string}>|Record<string,string>} input.attributes the user's current attributes (list or trigger-event map shape)
36
+ * @param {() => string} [input.mint] override the id minter (customer-overridable suid, D10)
37
+ * @param {(mint: () => string) => Promise<{ suid: string }>} [input.claim] the creation journal: offered this caller's
38
+ * minter, returns the one canonical suid for the user. The suid it returns is the one written, so concurrent minters
39
+ * write the same value. A claim that throws writes nothing.
40
+ * @param {(msg: string) => void} [input.log]
41
+ * @returns {Promise<{ suid: string, minted: boolean, verified: boolean }>} verified = the suid is the one Cognito persists
42
+ * (read from its attributes or confirmed by the re-read); false only when the post-mint re-read failed
43
+ */
44
+ async function ensureSuid({ cognito, userPoolId, username, attributes, mint, claim, log = () => {} }) {
45
+ const existing = getAttr(attributes, 'custom:suid')
46
+ if (existing) {
47
+ log(`ensureSuid: ${username} already has custom:suid — no-op (write-once)`)
48
+ return { suid: existing, minted: false, verified: true }
49
+ }
50
+ const suid = claim ? (await claim(mint || newId)).suid : (mint || newId)()
51
+ await cognito.send(new AdminUpdateUserAttributesCommand({
52
+ UserPoolId: userPoolId,
53
+ Username: username,
54
+ UserAttributes: [{ Name: 'custom:suid', Value: suid }],
55
+ }))
56
+ log(`ensureSuid: minted custom:suid=${suid} for ${username}`)
57
+ // Cognito has no conditional attribute write: a concurrent minter (PostConfirmation vs a first-token
58
+ // PreTokenGeneration lazy mint) may have written after us. Re-read and adopt whatever is persisted so every
59
+ // caller converges on the stored value. A failed re-read keeps ours (the write itself succeeded).
60
+ try {
61
+ const got = await cognito.send(new AdminGetUserCommand({ UserPoolId: userPoolId, Username: username }))
62
+ const persisted = getAttr(got && got.UserAttributes, 'custom:suid')
63
+ if (persisted && persisted !== suid) {
64
+ log(`ensureSuid: concurrent mint for ${username} — adopting persisted custom:suid`)
65
+ return { suid: persisted, minted: false, verified: true }
66
+ }
67
+ if (persisted === suid) return { suid, minted: true, verified: true }
68
+ } catch (err) {
69
+ log(`ensureSuid: re-read failed for ${username}: ${(err && err.name) || 'error'}`)
70
+ }
71
+ return { suid, minted: true, verified: false }
72
+ }
73
+
74
+ module.exports = { ensureSuid, getAttr, newId }