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.
Files changed (62) hide show
  1. package/bin/saaslayer.js +23 -11
  2. package/package.json +7 -7
  3. package/src/cdn-aws.js +67 -0
  4. package/src/cdn-publication.js +146 -0
  5. package/src/cdn-publisher.js +166 -0
  6. package/src/commands/cdn.js +66 -0
  7. package/src/commands/deploy.js +4 -3
  8. package/src/commands/lifecycle.js +20 -2
  9. package/src/commands/operations.js +8 -3
  10. package/src/commands/stacks.js +2 -0
  11. package/src/commands/users-management.js +2 -2
  12. package/src/deployments.js +5 -2
  13. package/src/module-catalog.js +15 -5
  14. package/src/sms/scope.js +4 -2
  15. package/src/source-branch.js +36 -0
  16. package/src/users-import/ids.js +1 -1
  17. package/templates/saaslayer-foundation.yml +215 -281
  18. package/vendor/config/login-domain.js +213 -0
  19. package/vendor/discovery/index.d.mts +109 -0
  20. package/vendor/discovery/index.mjs +409 -0
  21. package/vendor/ids/index.d.ts +21 -0
  22. package/vendor/ids/index.js +237 -0
  23. package/vendor/migrations/backups.js +118 -0
  24. package/vendor/migrations/child.js +78 -0
  25. package/vendor/migrations/credentials.js +103 -0
  26. package/vendor/migrations/errors.js +30 -0
  27. package/vendor/migrations/exec-child.js +78 -0
  28. package/vendor/migrations/gate.js +51 -0
  29. package/vendor/migrations/index.js +30 -0
  30. package/vendor/migrations/inventory.js +92 -0
  31. package/vendor/migrations/log.js +14 -0
  32. package/vendor/migrations/release.js +45 -0
  33. package/vendor/migrations/report.js +129 -0
  34. package/vendor/migrations/rules.js +104 -0
  35. package/vendor/migrations/run.js +311 -0
  36. package/vendor/migrations/session-policy.js +37 -0
  37. package/vendor/migrations/step-guard.js +82 -0
  38. package/vendor/operations/activity.d.ts +21 -0
  39. package/vendor/operations/activity.js +126 -0
  40. package/vendor/operations/index.d.ts +72 -0
  41. package/vendor/operations/index.js +510 -0
  42. package/vendor/permissions-engine-core/account-status.js +270 -0
  43. package/vendor/permissions-engine-core/delegation.js +174 -0
  44. package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
  45. package/vendor/permissions-engine-core/sso-claims.js +206 -0
  46. package/vendor/user-management/cognito/emails/token-registry.js +48 -0
  47. package/vendor/user-management/email/validate.js +207 -0
  48. package/vendor/user-management/extensibility/hook-contract.js +720 -0
  49. package/vendor/user-management/extensibility/safe-webhook.js +85 -0
  50. package/vendor/user-management/identity/admission.js +215 -0
  51. package/vendor/user-management/identity/attr.js +27 -0
  52. package/vendor/user-management/identity/attribute-registry.js +115 -0
  53. package/vendor/user-management/identity/email.js +25 -0
  54. package/vendor/user-management/identity/ensure-suid.js +74 -0
  55. package/vendor/user-management/identity/pointers.js +192 -0
  56. package/vendor/user-management/identity/stitch-provider.js +275 -0
  57. package/vendor/user-management/management/apply-request.js +227 -0
  58. package/vendor/user-management/management/core-profile.js +110 -0
  59. package/vendor/user-management/management/index.js +23 -0
  60. package/vendor/user-management/management/purposes.js +94 -0
  61. package/vendor/user-management/management/registry.js +569 -0
  62. package/vendor/user-management/store/table.js +332 -0
@@ -0,0 +1,192 @@
1
+ // Exact-lookup pointer rows in the core table (D11): SUB#<cognitoSub> and PROVIDER#<name>#<id> -> suid. Single-table
2
+ // key lookups, no index. Writes are conditional on the owner so a pointer is never silently re-pointed at another user.
3
+ const { GetCommand, PutCommand, DeleteCommand, UpdateCommand } = require('@aws-sdk/lib-dynamodb')
4
+ const { keys } = require('../store/table')
5
+
6
+ const POINTER_SK = 'POINTER'
7
+
8
+ /** @param {string} sub Cognito sub */
9
+ function subPointerKey(sub) {
10
+ return { pk: `SUB#${sub}`, sk: POINTER_SK }
11
+ }
12
+
13
+ /** @param {string} providerName e.g. Google @param {string} providerUserId the provider subject */
14
+ function providerPointerKey(providerName, providerUserId) {
15
+ return { pk: `PROVIDER#${providerName}#${providerUserId}`, sk: POINTER_SK }
16
+ }
17
+
18
+ /**
19
+ * Point key at suid. Durable (no exp). `attribute_not_exists(pk) OR suid = :suid`: first writer wins, the owner's
20
+ * rewrite is idempotent, and a pointer owned by another suid is reported, not overwritten.
21
+ * @param {{ send: Function }} doc
22
+ * @param {string} tableName
23
+ * @param {{ pk: string, sk: string }} key
24
+ * @param {string} suid
25
+ * @param {(...a: unknown[]) => void} [log]
26
+ * @returns {Promise<{ written: boolean, ownerSuid: string|null }>}
27
+ */
28
+ async function putPointer(doc, tableName, key, suid, log = console.log) {
29
+ try {
30
+ await doc.send(new PutCommand({
31
+ TableName: tableName,
32
+ Item: { ...key, itemType: 'POINTER', suid },
33
+ ConditionExpression: 'attribute_not_exists(pk) OR suid = :suid',
34
+ ExpressionAttributeValues: { ':suid': suid },
35
+ }))
36
+ return { written: true, ownerSuid: suid }
37
+ } catch (err) {
38
+ if (!err || err.name !== 'ConditionalCheckFailedException') throw err
39
+ log('pointer put:owned-by-other', key.pk.split('#')[0])
40
+ return { written: false, ownerSuid: await resolvePointer(doc, tableName, key) }
41
+ }
42
+ }
43
+
44
+ /**
45
+ * The transaction write behind putPointer's rule, for a pointer that must change together with another row: point a
46
+ * free pointer (or one suid already owns) at suid. A pointer owned by another suid cancels the whole transaction.
47
+ * @param {string} tableName
48
+ * @param {{ pk: string, sk: string }} key
49
+ * @param {string} suid
50
+ * @returns {{ Update: { TableName: string, Key: { pk: string, sk: string }, UpdateExpression: string, ConditionExpression: string, ExpressionAttributeValues: Record<string, string> } }}
51
+ */
52
+ function ownedPointerWrite(tableName, key, suid) {
53
+ return {
54
+ Update: {
55
+ TableName: tableName,
56
+ Key: key,
57
+ UpdateExpression: 'SET itemType = :type, suid = :suid',
58
+ ConditionExpression: 'attribute_not_exists(pk) OR suid = :suid',
59
+ ExpressionAttributeValues: { ':type': 'POINTER', ':suid': suid },
60
+ },
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Delete key only if it points at suid. Returns false when absent or owned by someone else.
66
+ * @param {{ send: Function }} doc
67
+ * @param {string} tableName
68
+ * @param {{ pk: string, sk: string }} key
69
+ * @param {string} suid
70
+ * @returns {Promise<boolean>}
71
+ */
72
+ async function deletePointer(doc, tableName, key, suid) {
73
+ try {
74
+ await doc.send(new DeleteCommand({
75
+ TableName: tableName,
76
+ Key: key,
77
+ ConditionExpression: 'suid = :suid',
78
+ ExpressionAttributeValues: { ':suid': suid },
79
+ }))
80
+ return true
81
+ } catch (err) {
82
+ if (!err || err.name !== 'ConditionalCheckFailedException') throw err
83
+ return false
84
+ }
85
+ }
86
+
87
+ /**
88
+ * @param {{ send: Function }} doc
89
+ * @param {string} tableName
90
+ * @param {{ pk: string, sk: string }} key
91
+ * @returns {Promise<string|null>} the suid the pointer names, or null
92
+ */
93
+ async function resolvePointer(doc, tableName, key) {
94
+ const res = await doc.send(new GetCommand({ TableName: tableName, Key: key }))
95
+ return (res && res.Item && res.Item.suid) || null
96
+ }
97
+
98
+ /**
99
+ * Linked federated identities from the Cognito `identities` attribute (a JSON string in trigger events and
100
+ * ListUsers/AdminGetUser attributes).
101
+ * @param {unknown} identities
102
+ * @returns {Array<{ providerName: string, userId: string }>}
103
+ */
104
+ function providerIdentities(identities) {
105
+ let arr = identities
106
+ if (typeof identities === 'string') {
107
+ try { arr = JSON.parse(identities) } catch { return [] }
108
+ }
109
+ if (!Array.isArray(arr)) return []
110
+ return arr
111
+ .filter((i) => i && i.providerName && i.userId !== undefined && i.userId !== null && i.userId !== '')
112
+ .map((i) => ({ providerName: String(i.providerName), userId: String(i.userId) }))
113
+ }
114
+
115
+ // Cognito provider types of enterprise SSO (a SAML or OIDC connection); social providers carry their own type names.
116
+ const ENTERPRISE_PROVIDER_TYPES = ['SAML', 'OIDC']
117
+
118
+ /**
119
+ * Whether a Cognito user's `identities` attribute names an enterprise SSO provider (SAML or OIDC): the user is an SSO
120
+ * credential (never linked into a native user, spec §7.2) and AWS bills it as an Enterprise MAU.
121
+ * @param {unknown} identities the attribute (a JSON string) or its parsed array
122
+ * @returns {boolean}
123
+ */
124
+ function enterpriseFederated(identities) {
125
+ let arr = identities
126
+ if (typeof identities === 'string') {
127
+ try { arr = JSON.parse(identities) } catch { return false }
128
+ }
129
+ return Array.isArray(arr) && arr.some((i) => i && ENTERPRISE_PROVIDER_TYPES.includes(i.providerType))
130
+ }
131
+
132
+ /**
133
+ * The external provider a federated-only account belongs to: the linked identity whose `<providerName>_<userId>` is the
134
+ * account's username (Cognito lowercases the social prefix, so compared without case). Null for a native account, linked
135
+ * providers included: its sign-in may have been its password.
136
+ * @param {string} userName
137
+ * @param {unknown} identities
138
+ * @returns {string|null}
139
+ */
140
+ function federatedOnlyProvider(userName, identities) {
141
+ const name = String(userName || '').toLowerCase()
142
+ const own = providerIdentities(identities).find((i) => `${i.providerName}_${i.userId}`.toLowerCase() === name)
143
+ return own ? own.providerName : null
144
+ }
145
+
146
+ /** The `<name>#<id>` reference stored in a PROFILE's `providers` set. @param {{ providerName: string, userId: string }} i */
147
+ function providerRef(i) {
148
+ return `${i.providerName}#${i.userId}`
149
+ }
150
+
151
+ // ADD/DELETE a provider ref on the PROFILE's providers set; a user not projected yet is a no-op (the sweep backfills).
152
+ async function updateProviderSet(doc, tableName, suid, op, ref) {
153
+ try {
154
+ await doc.send(new UpdateCommand({
155
+ TableName: tableName,
156
+ Key: keys.userProfile(suid),
157
+ UpdateExpression: `${op} providers :p`,
158
+ ConditionExpression: 'attribute_exists(pk)',
159
+ ExpressionAttributeValues: { ':p': new Set([ref]) },
160
+ }))
161
+ } catch (err) {
162
+ if (!err || err.name !== 'ConditionalCheckFailedException') throw err
163
+ }
164
+ }
165
+
166
+ /**
167
+ * A provider identity was linked to suid: point PROVIDER#<name>#<id> at suid and record it on the profile.
168
+ * @param {{ send: Function }} doc
169
+ * @param {string} tableName
170
+ * @param {{ suid: string, providerName: string, userId: string }} link
171
+ * @param {(...a: unknown[]) => void} [log]
172
+ * @returns {Promise<{ written: boolean, ownerSuid: string|null }>}
173
+ */
174
+ async function linkProviderPointer(doc, tableName, { suid, providerName, userId }, log) {
175
+ const res = await putPointer(doc, tableName, providerPointerKey(providerName, userId), suid, log)
176
+ if (res.written) await updateProviderSet(doc, tableName, suid, 'ADD', providerRef({ providerName, userId }))
177
+ return res
178
+ }
179
+
180
+ /**
181
+ * A provider identity was unlinked from suid: drop its pointer (if suid owns it) and its profile ref.
182
+ * @param {{ send: Function }} doc
183
+ * @param {string} tableName
184
+ * @param {{ suid: string, providerName: string, userId: string }} link
185
+ * @returns {Promise<void>}
186
+ */
187
+ async function unlinkProviderPointer(doc, tableName, { suid, providerName, userId }) {
188
+ await deletePointer(doc, tableName, providerPointerKey(providerName, userId), suid)
189
+ await updateProviderSet(doc, tableName, suid, 'DELETE', providerRef({ providerName, userId }))
190
+ }
191
+
192
+ module.exports = { ownedPointerWrite, providerRef, linkProviderPointer, unlinkProviderPointer, POINTER_SK, subPointerKey, providerPointerKey, putPointer, deletePointer, resolvePointer, providerIdentities, federatedOnlyProvider, enterpriseFederated }
@@ -0,0 +1,275 @@
1
+ // External-provider identity stitching (C1 / plan D2-D5, D9). On PreSignUp_ExternalProvider, resolve a
2
+ // federated sign-in to the ONE native Cognito user that owns the same verified email — link them so both
3
+ // methods share a single principal (custom:suid) — or refuse safely. Never guesses, never forks identity.
4
+
5
+ const {
6
+ ListUsersCommand,
7
+ AdminLinkProviderForUserCommand,
8
+ AdminGetUserCommand,
9
+ } = require('@aws-sdk/client-cognito-identity-provider')
10
+ const { getAttr } = require('./ensure-suid')
11
+ const { isTruthyAttr } = require('./attr')
12
+ const { normalizeEmail } = require('./email')
13
+ const { linkProviderPointer } = require('./pointers')
14
+
15
+ // Google's hd (hosted domain) claim, mapped to custom:idpDomain, read here for the D9 domain-lock guard.
16
+ // name/picture are provider-owned STANDARD attrs (Cognito maps them directly), so there is no carrier merge.
17
+ const IDP_DOMAIN = 'custom:idpDomain'
18
+
19
+ // What a refused federated sign-up tells the client: Cognito puts the trigger error on the managed-login callback, and the
20
+ // leading code is what widgets map to their own copy (the prose after it is never shown).
21
+ const HOSTED_DOMAIN_REFUSAL = 'SOCIAL_HOSTED_DOMAIN: this Google account is not in an allowed hosted domain.'
22
+ const EMAIL_EXISTS_REFUSAL = 'SOCIAL_EMAIL_EXISTS: an account already exists for this email. Sign in with your existing method to connect this login.'
23
+
24
+
25
+ // Cognito LOWERCASES the built-in social provider prefix in the federated userName (google_, facebook_,
26
+ // loginwithamazon_, signinwithapple_), even though the IdP — and the `identities` record Cognito writes —
27
+ // use the canonical mixed case (Google, Facebook, ...). Map back, so AdminLinkProviderForUser (whose
28
+ // SourceProviderName must match a configured provider) and the identities comparison both use the real
29
+ // name. A custom OIDC/SAML provider keeps its configured case in the prefix, so an unmapped name passes through.
30
+ const CANONICAL_PROVIDER = { google: 'Google', facebook: 'Facebook', loginwithamazon: 'LoginWithAmazon', signinwithapple: 'SignInWithApple' }
31
+ function canonicalProviderName(name) {
32
+ return CANONICAL_PROVIDER[String(name).toLowerCase()] || name
33
+ }
34
+
35
+ /**
36
+ * Only the built-in social providers are ever linked into a native account. Every other provider in the pool is an
37
+ * enterprise SSO connection (created at runtime): its login stays a separate Cognito user that user-service binds to the
38
+ * person (USER#<suid>/CREDENTIAL#sso:<connectionId>), so linking would reclassify direct users as SSO MAU (SSO spec §7.2).
39
+ * @param {string} providerName the canonical provider name (parseProviderIdentity)
40
+ * @returns {boolean}
41
+ */
42
+ function isLinkableProvider(providerName) {
43
+ return Object.values(CANONICAL_PROVIDER).includes(providerName)
44
+ }
45
+
46
+ /**
47
+ * Parse the ProviderName + provider subject out of a PreSignUp_ExternalProvider event userName. Cognito
48
+ * shapes it as `<provider>_<subject>` (e.g. `google_11223344`, `loginwithamazon_amzn1.account.ABC`) — the
49
+ * social prefix is lowercased, so the parsed name is canonicalized back to the configured IdP name.
50
+ * Split on the FIRST underscore only — Amazon subjects carry dots, never a leading underscore.
51
+ * @param {string} userName
52
+ * @returns {{ providerName: string, subject: string }|null}
53
+ */
54
+ function parseProviderIdentity(userName) {
55
+ const s = String(userName || '')
56
+ const i = s.indexOf('_')
57
+ if (i <= 0 || i === s.length - 1) return null
58
+ return { providerName: canonicalProviderName(s.slice(0, i)), subject: s.slice(i + 1) }
59
+ }
60
+
61
+ /** A pure federated shadow user (created by Cognito for federation) — never a link destination. */
62
+ function isFederatedOnly(user) {
63
+ return user && user.UserStatus === 'EXTERNAL_PROVIDER'
64
+ }
65
+
66
+ /** Read the linked identities off a Cognito user record ([{Name,Value}] Attributes shape). */
67
+ function readIdentities(user) {
68
+ const raw = getAttr(user && user.Attributes, 'identities')
69
+ if (!raw) return []
70
+ try {
71
+ const parsed = JSON.parse(raw)
72
+ return Array.isArray(parsed) ? parsed : []
73
+ } catch (err) {
74
+ return []
75
+ }
76
+ }
77
+
78
+ /** Is (providerName, subject) already present in this user's identities? */
79
+ function hasIdentity(user, providerName, subject) {
80
+ return readIdentities(user).some((id) =>
81
+ id && String(id.providerName) === providerName && String(id.userId) === subject)
82
+ }
83
+
84
+ /**
85
+ * Whether a ListUsers row is a native account that can OWN this email: native (not federated-only),
86
+ * matching email, enabled, and past signup confirmation. An UNCONFIRMED native is never an owner — anyone
87
+ * can create one for any address without proving control of it, so it must not squat the email (block or
88
+ * absorb the real owner's social login).
89
+ * @param {Object} u
90
+ * @param {string} email normalized (lowercase) email
91
+ * @returns {boolean}
92
+ */
93
+ function isOwningNative(u, email) {
94
+ return !isFederatedOnly(u) &&
95
+ normalizeEmail(getAttr(u.Attributes, 'email')) === email &&
96
+ u.Enabled !== false &&
97
+ u.UserStatus !== 'UNCONFIRMED'
98
+ }
99
+
100
+ /**
101
+ * Select the single native, verified, enabled candidate to link into, from a ListUsers result.
102
+ * @param {Array<Object>} users
103
+ * @param {string} email normalized (lowercase) email
104
+ * @returns {{ candidate?: Object, decision: 'link'|'refused'|'no-link', reason?: string }}
105
+ */
106
+ function selectCandidate(users, email) {
107
+ const natives = (users || []).filter((u) => isOwningNative(u, email))
108
+ if (natives.length === 0) {
109
+ return { decision: 'no-link', reason: 'no-native-match' }
110
+ }
111
+ const verified = natives.filter((u) => isTruthyAttr(getAttr(u.Attributes, 'email_verified')))
112
+ if (verified.length === 1) {
113
+ return { candidate: verified[0], decision: 'link' }
114
+ }
115
+ if (verified.length > 1) {
116
+ // Ambiguous: two verified natives share this email — never guess which owns it.
117
+ return { decision: 'no-link', reason: 'ambiguous' }
118
+ }
119
+ // A native account exists for this email but none is verified: the verified<->verified handshake fails.
120
+ // Do NOT create a second account — guide the user to their existing method (D3).
121
+ return { decision: 'refused', reason: 'unverified-native' }
122
+ }
123
+
124
+ /**
125
+ * Mark the event so Cognito completes the federated sign-in. autoConfirmUser always (the federated user
126
+ * is created either way); autoVerifyEmail only when the provider asserts a verified email.
127
+ */
128
+ function autoComplete(event, verified) {
129
+ if (!event.response) event.response = {}
130
+ event.response.autoConfirmUser = true
131
+ if (verified) event.response.autoVerifyEmail = true
132
+ return event
133
+ }
134
+
135
+ /**
136
+ * PreSignUp_ExternalProvider stitching (C1). Runs AFTER the config-driven signup allowlist gate.
137
+ * @param {Object} p
138
+ * @param {{ send: Function }} p.cognito Cognito Identity Provider client
139
+ * @param {string} p.userPoolId
140
+ * @param {Object} p.event the Cognito PreSignUp event
141
+ * @param {string[]} [p.googleHostedDomains] D9 allowlist; when non-empty, a Google login must carry a hd in it
142
+ * @param {(msg: string, ...a: any[]) => void} [p.log]
143
+ * @param {{ send: Function }} [p.doc] core-table document client; with tableName, a stitched link also writes the
144
+ * PROVIDER# pointer (D11), best-effort
145
+ * @param {string} [p.tableName]
146
+ * @param {() => Promise<void>} [p.beforeStandalone] asked once the built-in checks have decided this login becomes a
147
+ * new, standalone account (never for a link into an existing one); it throws to block the sign-up
148
+ * @returns {Promise<Object>} the event (mutated: autoConfirm/autoVerify), or throws to BLOCK the sign-in
149
+ */
150
+ async function stitchExternalProvider({ cognito, userPoolId, event, googleHostedDomains = [], log = () => {}, doc, tableName, beforeStandalone }) {
151
+ /** Complete the login as a new standalone account, once the sign-up admission (if any) lets it through. @param {boolean} emailVerified */
152
+ const standalone = async (emailVerified) => {
153
+ if (beforeStandalone) await beforeStandalone()
154
+ return autoComplete(event, emailVerified)
155
+ }
156
+ const attrs = (event.request && event.request.userAttributes) || {}
157
+ const email = normalizeEmail(attrs.email)
158
+ const identity = parseProviderIdentity(event.userName)
159
+ const verified = isTruthyAttr(attrs.email_verified)
160
+
161
+ if (!identity) {
162
+ console.error('stitch:bad_username', JSON.stringify({ event: 'bad_username', userName: event.userName || null }))
163
+ return standalone(verified) // can't stitch without a provider identity; let it stand alone
164
+ }
165
+ const { providerName, subject } = identity
166
+
167
+ // An enterprise SSO login is never stitched: no email lookup, no link, no PROVIDER# pointer. It completes as its own
168
+ // Cognito user; the SSO identity joins (src/sso/identity-joins.js) decide which person it belongs to.
169
+ if (!isLinkableProvider(providerName)) {
170
+ log('stitch:sso-separate provider=%s', providerName)
171
+ return standalone(verified)
172
+ }
173
+
174
+ // (D9) hd guard — Google only. When the deployment pins hosted domains, require a hd claim IN the list;
175
+ // a consumer @gmail account carries no hd (absent) -> reject. Non-Google providers have no hd concept.
176
+ if (providerName === 'Google' && googleHostedDomains.length) {
177
+ const hd = String(attrs[IDP_DOMAIN] || '').trim().toLowerCase()
178
+ if (!hd || !googleHostedDomains.map((d) => String(d).trim().toLowerCase()).includes(hd)) {
179
+ console.warn('stitch:hd_rejected', JSON.stringify({ event: 'hd_rejected', hd: hd || null, subject }))
180
+ throw new Error(HOSTED_DOMAIN_REFUSAL)
181
+ }
182
+ }
183
+
184
+ // (Step 1) verified-email guard. An unverified provider email with NO native match just stands alone;
185
+ // a native match while unverified is handled as REFUSED below (never a silent link on unverified email).
186
+ if (!email) {
187
+ return standalone(verified)
188
+ }
189
+
190
+ // (Step 3) find the destination: EXACTLY ONE native, verified, enabled account for this email.
191
+ const res = await cognito.send(new ListUsersCommand({
192
+ UserPoolId: userPoolId,
193
+ Filter: `email = "${email}"`,
194
+ Limit: 60,
195
+ }))
196
+ const users = res.Users || []
197
+
198
+ if (!verified) {
199
+ // Unverified provider email: only safe outcome is a standalone account, and ONLY if no native owns
200
+ // this email. If a native does, refuse rather than fork (attacker can't claim a verified account).
201
+ const anyNative = users.some((u) => isOwningNative(u, email))
202
+ if (anyNative) {
203
+ console.warn('stitch:refused', JSON.stringify({ event: 'refused', reason: 'unverified-provider-email', subject }))
204
+ throw new Error(EMAIL_EXISTS_REFUSAL)
205
+ }
206
+ return standalone(false)
207
+ }
208
+
209
+ const sel = selectCandidate(users, email)
210
+ if (sel.decision === 'refused') {
211
+ console.warn('stitch:refused', JSON.stringify({ event: 'refused', reason: sel.reason, subject }))
212
+ throw new Error(EMAIL_EXISTS_REFUSAL)
213
+ }
214
+ if (sel.decision === 'no-link') {
215
+ // Zero / duplicate / ambiguous / federated-only — never guess. Warn + let the account stand alone.
216
+ console.warn('stitch:no_link', JSON.stringify({ event: 'no_link', reason: sel.reason, subject, matches: users.length }))
217
+ return standalone(true)
218
+ }
219
+
220
+ const candidate = sel.candidate
221
+ const destUsername = candidate.Username
222
+ // Point the provider identity at the destination's suid (D11). Best-effort: a pointer failure never blocks sign-in.
223
+ const recordPointer = async () => {
224
+ const suid = getAttr(candidate.Attributes, 'custom:suid')
225
+ if (!doc || !tableName || !suid) return
226
+ try {
227
+ await linkProviderPointer(doc, tableName, { suid, providerName, userId: subject }, log)
228
+ } catch (err) {
229
+ console.warn('stitch:pointer_error', JSON.stringify({ event: 'pointer_error', error: (err && err.name) || null, subject }))
230
+ }
231
+ }
232
+
233
+ // (Step 5) already-linked -> success no-op.
234
+ if (hasIdentity(candidate, providerName, subject)) {
235
+ log('stitch:already-linked provider=%s subject=%s dest=%s', providerName, subject, destUsername)
236
+ await recordPointer()
237
+ return autoComplete(event, true)
238
+ }
239
+
240
+ // (Step 6) link the SUBJECT (never the email) of the source provider into the native destination user.
241
+ try {
242
+ await cognito.send(new AdminLinkProviderForUserCommand({
243
+ UserPoolId: userPoolId,
244
+ DestinationUser: { ProviderName: 'Cognito', ProviderAttributeValue: destUsername },
245
+ SourceUser: { ProviderName: providerName, ProviderAttributeName: 'Cognito_Subject', ProviderAttributeValue: subject },
246
+ }))
247
+ log('stitch:linked provider=%s subject=%s dest=%s', providerName, subject, destUsername)
248
+ } catch (err) {
249
+ // (Step 7) race: a concurrent link may have won. Re-read; succeed ONLY if that exact identity is now
250
+ // present, else surface the error (blocks — we never proceed on an unconfirmed link).
251
+ console.warn('stitch:link_conflict', JSON.stringify({ event: 'link_conflict', error: (err && err.name) || null, subject }))
252
+ const reread = await cognito.send(new AdminGetUserCommand({ UserPoolId: userPoolId, Username: destUsername }))
253
+ const rereadUser = { Attributes: (reread && reread.UserAttributes) || [] }
254
+ if (!hasIdentity(rereadUser, providerName, subject)) throw err
255
+ log('stitch:link_conflict_resolved provider=%s subject=%s', providerName, subject)
256
+ }
257
+
258
+ await recordPointer()
259
+
260
+ // name/picture are provider-owned standard attrs (Cognito maps them directly, overwriting each login) —
261
+ // no fill-if-empty profile merge in the simple model.
262
+ return autoComplete(event, true)
263
+ }
264
+
265
+ module.exports = {
266
+ stitchExternalProvider,
267
+ parseProviderIdentity,
268
+ isFederatedOnly,
269
+ readIdentities,
270
+ hasIdentity,
271
+ isLinkableProvider,
272
+ selectCandidate,
273
+ normalizeEmail,
274
+ IDP_DOMAIN,
275
+ }