saaslayer 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/bin/saaslayer.js +91 -6
  2. package/package.json +5 -6
  3. package/src/api-client.js +3 -2
  4. package/src/commands/foundation.js +5 -3
  5. package/src/commands/hooks.js +4 -9
  6. package/src/commands/operations.js +1 -1
  7. package/src/commands/release-manifest.js +3 -1
  8. package/src/commands/settings.js +2 -0
  9. package/src/commands/sms.js +35 -4
  10. package/src/commands/sso.js +913 -0
  11. package/src/commands/users-management.js +2 -2
  12. package/src/commands/users.js +7 -3
  13. package/src/commands/verifier-keys.js +105 -0
  14. package/src/login-domain.js +1 -0
  15. package/src/release-manifest.js +30 -7
  16. package/src/secret-sink.js +77 -0
  17. package/src/sms/registration-fields.js +1 -1
  18. package/src/sso-plan.js +21 -0
  19. package/src/user-service-instance.js +30 -1
  20. package/src/users-api.js +3 -2
  21. package/src/users-import/ids.js +1 -1
  22. package/templates/saaslayer-foundation-region.yml +10 -2
  23. package/templates/saaslayer-foundation.yml +33 -5
  24. package/vendor/config/login-domain.js +213 -0
  25. package/vendor/discovery/index.d.mts +109 -0
  26. package/vendor/discovery/index.mjs +409 -0
  27. package/vendor/ids/index.d.ts +21 -0
  28. package/vendor/ids/index.js +237 -0
  29. package/vendor/migrations/backups.js +118 -0
  30. package/vendor/migrations/child.js +78 -0
  31. package/vendor/migrations/credentials.js +103 -0
  32. package/vendor/migrations/errors.js +30 -0
  33. package/vendor/migrations/exec-child.js +78 -0
  34. package/vendor/migrations/gate.js +51 -0
  35. package/vendor/migrations/index.js +30 -0
  36. package/vendor/migrations/inventory.js +92 -0
  37. package/vendor/migrations/log.js +14 -0
  38. package/vendor/migrations/release.js +45 -0
  39. package/vendor/migrations/report.js +129 -0
  40. package/vendor/migrations/rules.js +104 -0
  41. package/vendor/migrations/run.js +311 -0
  42. package/vendor/migrations/session-policy.js +37 -0
  43. package/vendor/migrations/step-guard.js +82 -0
  44. package/vendor/operations/activity.d.ts +21 -0
  45. package/vendor/operations/activity.js +126 -0
  46. package/vendor/operations/index.d.ts +60 -0
  47. package/vendor/operations/index.js +471 -0
  48. package/vendor/permissions-engine-core/account-status.js +270 -0
  49. package/vendor/permissions-engine-core/delegation.js +174 -0
  50. package/vendor/permissions-engine-core/direct-mode-contract.js +237 -0
  51. package/vendor/permissions-engine-core/sso-claims.js +206 -0
  52. package/vendor/user-management/cognito/emails/token-registry.js +48 -0
  53. package/vendor/user-management/email/validate.js +207 -0
  54. package/vendor/user-management/extensibility/hook-contract.js +720 -0
  55. package/vendor/user-management/extensibility/safe-webhook.js +85 -0
  56. package/vendor/user-management/identity/admission.js +215 -0
  57. package/vendor/user-management/identity/attr.js +27 -0
  58. package/vendor/user-management/identity/attribute-registry.js +115 -0
  59. package/vendor/user-management/identity/email.js +25 -0
  60. package/vendor/user-management/identity/ensure-suid.js +74 -0
  61. package/vendor/user-management/identity/pointers.js +192 -0
  62. package/vendor/user-management/identity/stitch-provider.js +275 -0
  63. package/vendor/user-management/management/apply-request.js +227 -0
  64. package/vendor/user-management/management/core-profile.js +110 -0
  65. package/vendor/user-management/management/index.js +23 -0
  66. package/vendor/user-management/management/purposes.js +94 -0
  67. package/vendor/user-management/management/registry.js +569 -0
  68. package/vendor/user-management/store/table.js +332 -0
@@ -0,0 +1,332 @@
1
+ // Single-table data-access seam for user-service (epic monorepo-u1gh3, bead F1).
2
+ // Enforces the one invariant that makes table-scoped TTL safe: durable rows omit `exp`, transient rows carry it.
3
+ const { PutCommand } = require('@aws-sdk/lib-dynamodb')
4
+
5
+ /**
6
+ * Item-type tags. Stored on every row as `itemType` so a full-table scan (PITR restore,
7
+ * projection rebuild) can classify rows without parsing composite keys.
8
+ * @readonly
9
+ */
10
+ const ITEM = {
11
+ PROFILE: 'PROFILE', // durable: Cognito read-projection for a user (keyed on suid)
12
+ CONFIG: 'CONFIG', // durable: versioned runtime config (claim maps / hooks / templates)
13
+ REGISTRATION: 'REGISTRATION', // durable: an invitation registration job (mailbox proof + provisioning checkpoints)
14
+ ADMIN_BOOTSTRAP: 'ADMIN_BOOTSTRAP', // durable: the deployment's designated first admin and its bootstrap checkpoints
15
+ ORG_OWNER_RESTORE: 'ORG_OWNER_RESTORE', // durable: a declared org owner's account restore and its bootstrap checkpoints
16
+ CREDENTIAL_BINDING: 'CREDENTIAL_BINDING', // durable: one login credential (pool + sub) a suid owns, with its lifecycle
17
+ SSO_GROUP_STATE: 'SSO_GROUP_STATE', // durable: a person's current groups from one SSO connection, per authority source, with its tombstone
18
+ SSO_GROUP_AUTHORITY: 'SSO_GROUP_AUTHORITY', // durable: which source (sign-in, SCIM or none) owns an SSO connection's groups, and its generation
19
+ SSO_GROUP_AUTHORITY_CHANGE: 'SSO_GROUP_AUTHORITY_CHANGE', // durable: the audit row of one group-authority change of an SSO connection
20
+ ACCOUNT_AUTH_STATE: 'ACCOUNT_AUTH_STATE', // durable: an account's security version and its open revocation journal
21
+ CREDENTIAL_REVOCATION: 'CREDENTIAL_REVOCATION', // durable: one operation's sign-out of chosen credentials (a connection's deactivation)
22
+ CREDENTIAL_LATEST_REVOCATION: 'CREDENTIAL_LATEST_REVOCATION', // durable: the latest time any CREDENTIAL_REVOCATION revoked one credential (pool + sub)
23
+ SIGNUP_JOURNAL: 'SIGNUP_JOURNAL', // transient: an unconfirmed phone signup attempt (provenance for cleanup)
24
+ MFA_RECOVERY: 'MFA_RECOVERY', // durable: a user's hashed one-time MFA recovery codes + failed-attempt window
25
+ AUTH_CAPABILITY: 'AUTH_CAPABILITY', // durable: the deployment's committed ready sign-in pools and their revision
26
+ ADMISSION_JOURNAL: 'ADMISSION_JOURNAL', // durable: the one canonical suid chosen for a pool + sub before Cognito is written
27
+ ADMISSION: 'ADMISSION', // durable: an account's admission (pending, admitted or cancelled), one per suid
28
+ HOOK_EVENT: 'HOOK_EVENT', // durable: a lifecycle hook event reference (id, type, pinned config version, status); no payload
29
+ HOOK_CLAIMS: 'HOOK_CLAIMS', // transient: app: claims a beforeTokenIssue hook returned for one context and config version
30
+ HOOK_PAYLOAD: 'HOOK_PAYLOAD', // transient: a hook event's sent bytes or its first accepted reply, encrypted, kept 14 days
31
+ HOOK_LOG: 'HOOK_LOG', // transient: one hook call's metadata (no body, target or personal data), kept 14 days
32
+ IDENTITY_QUOTA: 'IDENTITY_QUOTA', // durable: the stored-identity counter (Cognito count + reservations since) for MaxStoredIdentities
33
+ IDENTITY_RESERVATION: 'IDENTITY_RESERVATION', // transient: one identity-creation operation's slot under MaxStoredIdentities
34
+ SSO_CONNECTION: 'SSO_CONNECTION', // durable: one enterprise SSO connection (settings, sealed secrets, lifecycle, version); a deleted one stays as a tombstone
35
+ SSO_CONNECTION_COUNT: 'SSO_CONNECTION_COUNT', // durable: how many undeleted SSO connections the instance holds, under SsoMaxConnections
36
+ SSO_CONNECTION_RUNTIME: 'SSO_CONNECTION_RUNTIME', // durable: one SSO connection's Cognito provider + dedicated client in one pool, its operation journal and last operation
37
+ SSO_DIRECTORY_IDENTITY: 'SSO_DIRECTORY_IDENTITY', // durable: one immutable directory identity of an SSO connection, the person it joins and its active/inactive/deleted state
38
+ SSO_PROVIDER_SUBJECT: 'SSO_PROVIDER_SUBJECT', // durable: an SSO connection's provider login subject -> the directory identity it signs in as
39
+ SSO_PROVIDER_SUBJECT_FOLDED: 'SSO_PROVIDER_SUBJECT_FOLDED', // durable: an SSO connection's lowercased login subject -> its exact subject (case-insensitive pools lowercase usernames)
40
+ SSO_SCIM_CREDENTIAL: 'SSO_SCIM_CREDENTIAL', // durable: one slot of an SSO connection's SCIM bearer credentials (a digest, never the token)
41
+ SSO_DOMAIN_CLAIM: 'SSO_DOMAIN_CLAIM', // durable: the one SSO connection that owns a DNS-verified email domain on this instance
42
+ SSO_CONNECTION_DELETION: 'SSO_CONNECTION_DELETION', // durable: one SSO connection's delete journal (policy, steps reached, people done), kept as its record
43
+ SSO_TURN_OFF_HOLD: 'SSO_TURN_OFF_HOLD', // durable: EnableSso is being turned off: connection creates are refused until it expires
44
+ SSO_SCIM_RESOURCE: 'SSO_SCIM_RESOURCE', // durable: one SCIM User or Group of an SSO connection; a deleted one stays as a tombstone so its id is never reused
45
+ SSO_SCIM_UNIQUE: 'SSO_SCIM_UNIQUE', // durable: a unique SCIM key (externalId, userName, group displayName) held by one live resource of a connection
46
+ SSO_SCIM_GROUP_VERSION: 'SSO_SCIM_GROUP_VERSION', // durable: the version counter of a person's SCIM group writes for one SSO connection
47
+ SSO_SCIM_MEMBERSHIP: 'SSO_SCIM_MEMBERSHIP', // durable: one SCIM User's membership in one SCIM Group of an SSO connection (a row on each side)
48
+ SSO_SCIM_PENDING: 'SSO_SCIM_PENDING', // durable: a SCIM membership change whose user has not been synced since (cleared after the sync)
49
+ SSO_BREAK_GLASS_GRANT: 'SSO_BREAK_GLASS_GRANT', // durable: a person's live break-glass exemption from one SSO connection's domain enforcement, until its expiry
50
+ SSO_BREAK_GLASS_USE: 'SSO_BREAK_GLASS_USE', // durable: the audit row of one break-glass sign-in exemption opened on an SSO connection
51
+ SSO_ENFORCEMENT_RUN: 'SSO_ENFORCEMENT_RUN', // durable: one scheduled domain-enforcement cutover of an SSO connection: notices sent and native sign-outs journaled
52
+ SSO_HEALTH_SIGNAL: 'SSO_HEALTH_SIGNAL', // durable: one health signal of an SSO connection (last sign-in, last failure per category, SCIM outcome, certificate check)
53
+ SSO_HEALTH_ALERT: 'SSO_HEALTH_ALERT', // durable: the audit row of one SSO connection health alert (certificate expiry, domain check): who was mailed, when, retries
54
+ EMAIL_DOMAIN_BACKFILL: 'EMAIL_DOMAIN_BACKFILL', // durable: the one-time backfill of PROFILE emailDomain (email-domain-index) and its scan checkpoint
55
+ SSO_GROUP_DELIVERY: 'SSO_GROUP_DELIVERY', // durable: a person's SSO group state for one connection changed and is not yet confirmed delivered to permissions
56
+ VERIFIER_KEY: 'VERIFIER_KEY', // durable: one slot of a customer verifier key scope (a digest, never the key)
57
+ VERIFIER_KEY_EVENT: 'VERIFIER_KEY_EVENT', // durable: the audit row of one customer verifier key creation (its one reveal) or revocation
58
+ SSO_GROUP_REPLAY: 'SSO_GROUP_REPLAY', // durable: an SSO connection's group authority changed (or an operator asked), so every person's group state is delivered again
59
+ SSO_GROUP_REPLAY_REQUEST: 'SSO_GROUP_REPLAY_REQUEST', // durable: the audit row of one operator replay of an SSO connection's group states
60
+ SSO_MANAGEMENT_SESSION: 'SSO_MANAGEMENT_SESSION', // transient: one scoped SSO management session (a digest, never the token), reaped after its absolute limit
61
+ SSO_SETUP_LINK: 'SSO_SETUP_LINK', // transient: an SSO connection's one setup link for its IT admin (a digest, never the token), reaped after the sessions it may open
62
+ SSO_STEP_UP_FACTOR: 'SSO_STEP_UP_FACTOR', // durable: one SaaSLayer second factor (TOTP, sealed secret; or a step-up-only passkey) of a person's SSO credential
63
+ SSO_AUDIT_EVENT: 'SSO_AUDIT_EVENT', // durable: one redacted SSO audit event (management, setup, SCIM, authority, sign-in) of a connection, tenant or the deployment
64
+ SSO_STEP_UP_FACTOR_PENDING: 'SSO_STEP_UP_FACTOR_PENDING', // transient: an unconfirmed TOTP enrollment (sealed secret) or a passkey ceremony challenge of an SSO credential
65
+ }
66
+
67
+ // The retained bytes beside a hook event: what was sent, and the first accepted reply.
68
+ const HOOK_PAYLOAD_KINDS = ['payload', 'reply']
69
+
70
+ /**
71
+ * Is this key a retained hook payload or reply (HOOKEVT#<suid> / <type>#payload|reply), not an event?
72
+ * @param {{ pk?: unknown, sk?: unknown }} key
73
+ * @returns {boolean}
74
+ */
75
+ function isHookPayloadKey(key) {
76
+ const sk = String(key.sk || '')
77
+ return String(key.pk || '').startsWith('HOOKEVT#') && HOOK_PAYLOAD_KINDS.some((kind) => sk.endsWith(`#${kind}`))
78
+ }
79
+
80
+ // The login methods a credential binding (USER#<suid>/CREDENTIAL#<loginMethod>) can name.
81
+ const LOGIN_METHODS = ['email', 'phone']
82
+
83
+ // A durable partition is one of these composite-key shapes. Everything else is transient and
84
+ // MUST carry `exp`. Kept as a predicate on the KEY (not itemType) so the guard holds even if a
85
+ // caller forgets to tag itemType.
86
+ function isDurableItem(item) {
87
+ const sk = String(item.sk || '')
88
+ if (sk === 'PROFILE' || sk === 'LASTLOGIN') return true
89
+ if (item.pk === 'CONFIG#') return true
90
+ // exact-lookup pointers (SUB#/PROVIDER# -> suid) and email claims (EMAIL#)
91
+ if (sk === 'POINTER' || sk === 'CLAIM') return true
92
+ // invitation registration jobs (one per invitation; a resumable record of who registered)
93
+ if (sk === 'REGISTRATION') return true
94
+ // how the user was onboarded (an invitation-registered user never gets a personal org)
95
+ if (sk === 'ONBOARDING') return true
96
+ // the creation journal (canonical suid per pool + sub) and the account's admission marker
97
+ if (sk === 'JOURNAL' && String(item.pk || '').startsWith('ADMISSION#')) return true
98
+ if (sk === 'ADMISSION') return true
99
+ // lifecycle hook events: the durable record that an event was emitted (it outlives any payload or log); a sign-in
100
+ // event is a best-effort notification and expires, and so does an SSO lifecycle event once past its delivery window
101
+ if (String(item.pk || '').startsWith('HOOKEVT#')) return !isHookPayloadKey(item) && !sk.startsWith('user.signed_in#') && !sk.startsWith('sso.')
102
+ // server-owned credential bindings, one per login method a suid owns
103
+ if (LOGIN_METHODS.some((m) => sk === `CREDENTIAL#${m}`)) return true
104
+ // a person's credential from one SSO connection (a separate federated Cognito user), one per connection
105
+ if (sk.length > 'CREDENTIAL#sso:'.length && sk.startsWith('CREDENTIAL#sso:')) return true
106
+ // an SSO connection's directory identities and provider login subjects (identity joins)
107
+ if (String(item.pk || '').startsWith('SSOIDENT#')) return true
108
+ // a person's SSO group state per connection, and each connection's group authority with its change audit
109
+ if (sk.startsWith('SSOGROUPS#') || String(item.pk || '').startsWith('SSOGROUPAUTH#')) return true
110
+ // an account's security version (revocation checkpoint + journal), one per suid
111
+ if (sk === 'AUTHSTATE' && String(item.pk || '').startsWith('ACCOUNT#')) return true
112
+ // one operation's sign-out journal over chosen credentials of an account (never moves its security version)
113
+ if (sk.startsWith('CREDREVOKE#') && String(item.pk || '').startsWith('ACCOUNT#')) return true
114
+ // the latest time those journals revoked one credential of the account (what the live SSO standing reads)
115
+ if (sk.startsWith('CREDREVOKEDAT#') && String(item.pk || '').startsWith('ACCOUNT#')) return true
116
+ // hashed MFA recovery codes (plaintext is shown once and never stored)
117
+ if (sk === 'MFARECOVERY') return true
118
+ // a person's SSO step-up factors per connection (their pending enrollments and ceremony challenges are transient)
119
+ if (sk.startsWith('SSOFACTOR#')) return true
120
+ // the deployment's first-admin bootstrap (designated identity + delivery checkpoint)
121
+ if (item.pk === 'ADMIN_BOOTSTRAP#') return true
122
+ // a declared org owner's account restore (exact suid + delivery checkpoint), one per owner suid
123
+ if (item.pk === 'ORG_OWNER_RESTORE#') return true
124
+ // the deployment's committed sign-in capability (ready pools), one per deployment
125
+ if (item.pk === 'AUTH_CAPABILITY#') return true
126
+ // the stored-identity counter (its reservations are transient)
127
+ if (item.pk === 'IDQUOTA#') return item.sk === 'COUNTER'
128
+ // enterprise SSO connections, their tombstones and their counter
129
+ if (item.pk === 'SSOCONN#') return true
130
+ // an SSO connection's SCIM bearer credential slots (revoked and expired ones stay until the slot is reused)
131
+ if (String(item.pk || '').startsWith('SSOSCIMCRED#')) return true
132
+ // customer verifier key slots (a revoked one stays until its slot is reused) and their audit rows
133
+ if (item.pk === 'VERIFIERKEY#') return true
134
+ // an SSO connection's SCIM Users and Groups (tombstones included), the unique keys live ones hold, group memberships
135
+ // and their pending sync marks
136
+ if (String(item.pk || '').startsWith('SSOSCIM#')) return true
137
+ // a person's SCIM group-write version per SSO connection (group state ordering never goes backwards)
138
+ if (sk.startsWith('SSOSCIMSEQ#')) return true
139
+ // SSO group-state deliveries not yet confirmed by permissions, and connections whose group state is delivered again
140
+ if (item.pk === 'SSOGROUPSYNC#') return true
141
+ // the SSO audit trail: one partition per connection, per tenant (events bound to no connection) and the deployment
142
+ if (String(item.pk || '').startsWith('SSOAUDIT#')) return true
143
+ // an SSO connection's health signals and the audit rows of its health alerts
144
+ if (String(item.pk || '').startsWith('SSOHEALTH#')) return true
145
+ return false
146
+ }
147
+
148
+ /**
149
+ * Composite-key builders. Centralised so key shapes live in exactly one place — the projection and the
150
+ * REST API address core-table rows through these. Passwordless rows live in their own tables.
151
+ */
152
+ const keys = {
153
+ // durable
154
+ userProfile: (suid) => ({ pk: `USER#${suid}`, sk: 'PROFILE' }),
155
+ // last sign-in, unindexed, so logins never rewrite the indexed PROFILE (D13)
156
+ userLastLogin: (suid) => ({ pk: `USER#${suid}`, sk: 'LASTLOGIN' }),
157
+ // how the user was onboarded (e.g. through an invitation), read before any personal-org bootstrap
158
+ userOnboarding: (suid) => ({ pk: `USER#${suid}`, sk: 'ONBOARDING' }),
159
+ // the account's admission: whether its creation reached a known onboarding outcome (pending, admitted or cancelled)
160
+ userAdmission: (suid) => ({ pk: `USER#${suid}`, sk: 'ADMISSION' }),
161
+ // a lifecycle hook event of the account, by event type (user.created: one per account)
162
+ hookEvent: (suid, type) => ({ pk: `HOOKEVT#${suid}`, sk: type }),
163
+ // an event not yet confirmed on the hooks queue, in the order it occurred; the reconcile sweep publishes what is left
164
+ hookEventPending: (occurredAt, suid) => ({ pk: 'HOOKEVT#pending', sk: `${occurredAt}#${suid}` }),
165
+ // a hook event's retained bytes, beside it: kind 'payload' (the envelope sent) or 'reply' (the first accepted reply)
166
+ hookPayload: (suid, type, kind) => ({ pk: `HOOKEVT#${suid}`, sk: `${type}#${kind}` }),
167
+ // one sign-in of the account (user.signed_in), keyed by its event id; transient
168
+ hookSignIn: (suid, eventId) => ({ pk: `HOOKEVT#${suid}`, sk: `user.signed_in#${eventId}` }),
169
+ // one SSO lifecycle event of a connection (ssoLifecycle hook), keyed by its type and event id; transient
170
+ ssoLifecycleEvent: (connectionId, type, eventId) => ({ pk: `HOOKEVT#SSO#${connectionId}`, sk: `${type}#${eventId}` }),
171
+ // the delivery log of one hook point
172
+ hookLogPartition: (point) => `HOOKLOG#${point}`,
173
+ // one hook call in the delivery log, under its point, newest-sortable by when it was recorded (at: ISO-8601 UTC)
174
+ hookLog: (point, at, eventId, attempt) => ({ pk: `HOOKLOG#${point}`, sk: `${at}#${eventId}#${attempt}` }),
175
+ // the creation journal: the one canonical suid for a Cognito user, chosen before its custom:suid is written
176
+ admissionJournal: (userPoolId, sub) => ({ pk: `ADMISSION#${userPoolId}#${sub}`, sk: 'JOURNAL' }),
177
+ // hashed one-time MFA recovery codes for the user (one row, replaced on regeneration)
178
+ userMfaRecovery: (suid) => ({ pk: `USER#${suid}`, sk: 'MFARECOVERY' }),
179
+ // one step-up factor of a person's SSO credential: kind TOTP, or PASSKEY#<credentialId> (durable)
180
+ ssoStepUpFactor: (suid, connectionId, kind) => ({ pk: `USER#${suid}`, sk: `SSOFACTOR#${connectionId}#${kind}` }),
181
+ // an SSO credential's unconfirmed TOTP enrollment (TOTP) or passkey ceremony challenge (CHALLENGE#<challenge>) (transient)
182
+ ssoStepUpFactorPending: (suid, connectionId, kind) => ({ pk: `USER#${suid}`, sk: `SSOFACTORPENDING#${connectionId}#${kind}` }),
183
+ configCurrent: () => ({ pk: 'CONFIG#', sk: 'CURRENT' }),
184
+ configVersion: (n) => ({ pk: 'CONFIG#', sk: `V#${String(n).padStart(10, '0')}` }),
185
+ // per-instance email authoring DRAFT (E3, D-i) — one item holding per-trigger content + a brand
186
+ // slice, OFF the hot path (runtime reads only CONFIG#/CURRENT); publish promotes a slice into config.
187
+ configDraft: () => ({ pk: 'CONFIG#', sk: 'DRAFT' }),
188
+ // per-trigger email fallback observability (E2) — written from the send path, OFF the config version
189
+ // chain (never mutates CONFIG#/CURRENT), read by the console to badge a fallen-back template.
190
+ emailStatus: (triggerSource) => ({ pk: 'EMAIL_STATUS#', sk: String(triggerSource) }),
191
+ // invitation registration job, one per invitation (mailbox proof, lease, provisioning checkpoints)
192
+ registrationJob: (invitationId) => ({ pk: `REGJOB#${invitationId}`, sk: 'REGISTRATION' }),
193
+ // the deployment's designated first admin, one per deployment (identity, grant, delivery checkpoint, activation)
194
+ adminBootstrap: () => ({ pk: 'ADMIN_BOOTSTRAP#', sk: 'FIRST_ADMIN' }),
195
+ // a declared org owner's account restore, one per owner suid (identity, membership check, delivery checkpoint, activation)
196
+ orgOwnerRestore: (suid) => ({ pk: 'ORG_OWNER_RESTORE#', sk: suid }),
197
+ // the deployment's committed sign-in capability: which pools are ready (opted-in deployments only)
198
+ authCapability: () => ({ pk: 'AUTH_CAPABILITY#', sk: 'CURRENT' }),
199
+ // one login credential (exact userPoolId + sub) a suid owns, with its pending/active/disconnected/tombstoned lifecycle;
200
+ // loginMethod is a native method (email, phone) or sso:<connectionId>
201
+ credentialBinding: (suid, loginMethod) => ({ pk: `USER#${suid}`, sk: `CREDENTIAL#${loginMethod}` }),
202
+ // a person's current groups from one SSO connection (sign-in and SCIM slots, drift, active/tombstone)
203
+ ssoGroupState: (suid, connectionId) => ({ pk: `USER#${suid}`, sk: `SSOGROUPS#${connectionId}` }),
204
+ // an SSO connection's group authority (signin | scim | none), its generation and any pending switch to SCIM
205
+ ssoGroupAuthority: (connectionId) => ({ pk: `SSOGROUPAUTH#${connectionId}`, sk: 'CURRENT' }),
206
+ // the audit row of the group-authority change that produced a generation
207
+ ssoGroupAuthorityChange: (connectionId, generation) => ({ pk: `SSOGROUPAUTH#${connectionId}`, sk: `CHANGE#${String(generation).padStart(10, '0')}` }),
208
+ // one immutable directory identity of an SSO connection (Okta user id, Entra tid/oid, Google sub) and the person it joins
209
+ ssoDirectoryIdentity: (connectionId, directoryId) => ({ pk: `SSOIDENT#${connectionId}`, sk: `DIR#${directoryId}` }),
210
+ // an SSO connection's provider login subject (OIDC sub or SAML NameID, exact case) -> the directory identity it signs in as
211
+ ssoProviderSubject: (connectionId, subject) => ({ pk: `SSOIDENT#${connectionId}`, sk: `SUBJECT#${subject}` }),
212
+ // an SSO connection's lowercased login subject -> its exact subject: a case-insensitive user pool lowercases the federated
213
+ // username `<providerName>_<subject>`, so a trigger after inbound federation recovers the exact subject through it
214
+ ssoProviderSubjectFolded: (connectionId, subject) => ({ pk: `SSOIDENT#${connectionId}`, sk: `SUBJECTCI#${String(subject).toLowerCase()}` }),
215
+ // an account's security version, floor and open revocation journal, one per suid
216
+ accountAuthState: (suid) => ({ pk: `ACCOUNT#${suid}`, sk: 'AUTHSTATE' }),
217
+ // one operation's sign-out journal over chosen credentials of an account (a connection's deactivation), one per opId
218
+ credentialRevocation: (suid, opId) => ({ pk: `ACCOUNT#${suid}`, sk: `CREDREVOKE#${opId}` }),
219
+ // the latest time any of those journals revoked one credential (exact userPoolId + sub) of the account, one per credential
220
+ credentialLatestRevocation: (suid, { userPoolId, sub }) => ({ pk: `ACCOUNT#${suid}`, sk: `CREDREVOKEDAT#${userPoolId}/${sub}` }),
221
+ // phone ownership claim, keyed by the destination digest (never the raw number)
222
+ phoneClaim: (digest) => ({ pk: `PHONE#${digest}`, sk: 'CLAIM' }),
223
+ // the stored-identity counter under MaxStoredIdentities, one per deployment
224
+ identityQuota: () => ({ pk: 'IDQUOTA#', sk: 'COUNTER' }),
225
+ // one enterprise SSO connection of this instance (the table is per instance, so the partition is too)
226
+ ssoConnection: (connectionId) => ({ pk: 'SSOCONN#', sk: `CONN#${connectionId}` }),
227
+ // the instance's undeleted SSO connection count, held under SsoMaxConnections
228
+ ssoConnectionCount: () => ({ pk: 'SSOCONN#', sk: 'COUNTER' }),
229
+ // one SSO connection's runtime Cognito resources in one user pool (the registry is keyed per pool, never by name alone)
230
+ ssoConnectionRuntime: (userPoolId, connectionId) => ({ pk: 'SSOCONN#', sk: `RUNTIME#${userPoolId}#${connectionId}` }),
231
+ // one of an SSO connection's SCIM bearer credential slots (1..SCIM_MAX_ACTIVE_CREDENTIALS)
232
+ ssoScimCredential: (connectionId, slot) => ({ pk: `SSOSCIMCRED#${connectionId}`, sk: `SLOT#${slot}` }),
233
+ // the SSO connection that owns a DNS-verified email domain (lower-case, exact): one owner per domain per instance
234
+ ssoDomainClaim: (domain) => ({ pk: 'SSOCONN#', sk: `DOMAIN#${domain}` }),
235
+ // one SSO connection's delete journal: enforcement off, trust revoked, its people released, its provider retired
236
+ ssoConnectionDeletion: (connectionId) => ({ pk: 'SSOCONN#', sk: `DELETION#${connectionId}` }),
237
+ // the instance's EnableSso turn-off hold, set by the deployer before it turns SSO off (one per instance)
238
+ ssoTurnOffHold: () => ({ pk: 'SSOCONN#', sk: 'TURNOFF' }),
239
+ // one SCIM User or Group of an SSO connection, by its server-assigned id
240
+ ssoScimResource: (connectionId, type, id) => ({ pk: `SSOSCIM#${connectionId}`, sk: `${type === 'Group' ? 'GROUP' : 'USER'}#${id}` }),
241
+ // a unique SCIM key of a connection's Users or Groups, by a digest of its normalized value; names the live holder
242
+ ssoScimUnique: (connectionId, type, key, digest) => ({ pk: `SSOSCIM#${connectionId}`, sk: `UNIQUE#${type === 'Group' ? 'GROUP' : 'USER'}#${key}#${digest}` }),
243
+ // one SCIM Group's member, by group (lists a group's members) and by user (lists a user's groups)
244
+ ssoScimMember: (connectionId, groupId, userId) => ({ pk: `SSOSCIM#${connectionId}`, sk: `MEMBER#${groupId}#${userId}` }),
245
+ ssoScimMemberOf: (connectionId, userId, groupId) => ({ pk: `SSOSCIM#${connectionId}`, sk: `MEMBEROF#${userId}#${groupId}` }),
246
+ // a group + user whose SCIM membership changed and whose user is not yet synced (written with the change)
247
+ ssoScimPending: (connectionId, groupId, userId) => ({ pk: `SSOSCIM#${connectionId}`, sk: `SYNC#${groupId}#${userId}` }),
248
+ // the version counter of a person's SCIM group writes for one SSO connection (taken before each membership read)
249
+ ssoScimGroupVersion: (suid, connectionId) => ({ pk: `USER#${suid}`, sk: `SSOSCIMSEQ#${connectionId}` }),
250
+ // a person's SSO group state for one connection awaiting delivery to permissions (one partition: the reconcile sweep lists it)
251
+ ssoGroupDelivery: (connectionId, suid) => ({ pk: 'SSOGROUPSYNC#', sk: `PERSON#${connectionId}#${suid}` }),
252
+ // an SSO connection whose every person's group state is delivered again (its group authority changed, or an operator asked)
253
+ ssoGroupReplay: (connectionId) => ({ pk: 'SSOGROUPSYNC#', sk: `CONNECTION#${connectionId}` }),
254
+ // the audit row of one operator replay of an SSO connection's group states, in time order per connection
255
+ ssoGroupReplayRequest: (connectionId, at, replayId) => ({ pk: `SSOGROUPAUTH#${connectionId}`, sk: `REPLAY#${at}#${replayId}` }),
256
+ // the SSO audit trail partition of a connection (its id), a tenant (TENANT#<tenant>) or the deployment (DEPLOYMENT)
257
+ ssoAuditPartition: (partition) => `SSOAUDIT#${partition}`,
258
+ // one SSO audit event in its partition, in time order (at: ISO-8601 UTC)
259
+ ssoAuditEvent: (partition, at, eventId) => ({ pk: `SSOAUDIT#${partition}`, sk: `EVENT#${at}#${eventId}` }),
260
+ // one health signal of an SSO connection: SIGNIN, FAILURE#<category>, SCIM#OK, SCIM#ERROR or CERT
261
+ ssoHealth: (connectionId, signal) => ({ pk: `SSOHEALTH#${connectionId}`, sk: signal }),
262
+ // the audit row of one health alert of an SSO connection, by its dedupe key (CERT#<expiresAt>#<days>, DOMAIN#…)
263
+ ssoHealthAlert: (connectionId, alertKey) => ({ pk: `SSOHEALTH#${connectionId}`, sk: `ALERT#${alertKey}` }),
264
+ // transient
265
+ // one scoped SSO management session (one tenant, optionally one connection), by its id
266
+ ssoManagementSession: (sessionId) => ({ pk: `SSOMGMT#${sessionId}`, sk: 'SESSION' }),
267
+ // an SSO connection's one setup link (issuing another replaces it)
268
+ ssoSetupLink: (connectionId) => ({ pk: `SSOSETUP#${connectionId}`, sk: 'LINK' }),
269
+ // one identity-creation operation's reserved slot, keyed by its operation key (a hash of pool + identifier)
270
+ identityReservation: (key) => ({ pk: 'IDQUOTA#', sk: `RESERVATION#${key}` }),
271
+ // a native credential link/number-change intent journal, one per (suid, kind, loginMethod)
272
+ nativeLink: (suid, kind, loginMethod) => ({ pk: `USER#${suid}`, sk: `NATIVELINK#${kind}#${loginMethod}` }),
273
+ // cached beforeTokenIssue claims of an account, one row per issuance context (a hash) and config version
274
+ hookClaims: (suid, contextKey) => ({ pk: `HOOKCLAIMS#${suid}`, sk: contextKey }),
275
+ // an unconfirmed phone signup attempt, one per (pool, Cognito user name)
276
+ signupJournal: (userPoolId, userName) => ({ pk: `SIGNUP#${userPoolId}#${userName}`, sk: 'JOURNAL' }),
277
+ // durable (SSOCONN#): a person's break-glass exemption from one connection's domain enforcement (expiresAt, no TTL)
278
+ ssoBreakGlassGrant: (connectionId, suid) => ({ pk: 'SSOCONN#', sk: `BREAKGLASS#${connectionId}#${suid}` }),
279
+ // durable (SSOCONN#): the audit row of one break-glass use, in time order per connection
280
+ ssoBreakGlassUse: (connectionId, at, suid) => ({ pk: 'SSOCONN#', sk: `BREAKGLASSUSE#${connectionId}#${at}#${suid}` }),
281
+ // durable (SSOCONN#): one connection's enforcement run for one scheduled cutover (notices, cutover sign-out journal)
282
+ ssoEnforcementRun: (connectionId, cutoverAt) => ({ pk: 'SSOCONN#', sk: `ENFORCEMENT#${connectionId}#${cutoverAt}` }),
283
+ // durable (VERIFIERKEY#): one slot (1..2) of a customer verifier key scope (trusted-clients, token-status)
284
+ verifierKeySlot: (scope, slot) => ({ pk: 'VERIFIERKEY#', sk: `SLOT#${scope}#${slot}` }),
285
+ // durable (VERIFIERKEY#): the audit row of one verifier key event (created, revoked), in time order
286
+ verifierKeyEvent: (at, keyId, event) => ({ pk: 'VERIFIERKEY#', sk: `AUDIT#${at}#${keyId}#${event}` }),
287
+ // durable (SSOCONN#): the one-time PROFILE emailDomain backfill the enforcement job runs before its first sweep
288
+ emailDomainBackfill: () => ({ pk: 'SSOCONN#', sk: 'EMAILDOMAIN_BACKFILL' }),
289
+ }
290
+
291
+ function nowSeconds() {
292
+ return Math.floor(Date.now() / 1000)
293
+ }
294
+
295
+ /**
296
+ * Write a durable row. Rejects any item carrying `exp` — a durable row with a TTL attribute would
297
+ * be silently deleted by DynamoDB TTL, which is exactly the class of bug this seam exists to prevent.
298
+ * @param {{ send: Function }} doc DynamoDBDocumentClient (or a stub with .send)
299
+ * @param {string} tableName
300
+ * @param {Record<string, any>} item
301
+ * @param {Record<string, any>} [opts] extra PutCommand input (e.g. ConditionExpression)
302
+ * @returns {Promise<Record<string, any>>} the written item
303
+ */
304
+ async function putDurable(doc, tableName, item, opts = {}) {
305
+ if (item.exp !== undefined) {
306
+ throw new Error('putDurable: durable items must not carry `exp` (table TTL would reap them)')
307
+ }
308
+ await doc.send(new PutCommand({ TableName: tableName, Item: item, ...opts }))
309
+ return item
310
+ }
311
+
312
+ /**
313
+ * Write a transient row, stamping `exp = now + ttlSeconds`. A positive ttl is required — a
314
+ * transient row without a TTL never gets reaped and accumulates forever.
315
+ * @param {{ send: Function }} doc
316
+ * @param {string} tableName
317
+ * @param {Record<string, any>} item
318
+ * @param {number} ttlSeconds must be > 0
319
+ * @param {() => number} [now] injectable clock (unix seconds) for tests
320
+ * @param {Record<string, any>} [opts] extra PutCommand input (e.g. ConditionExpression)
321
+ * @returns {Promise<Record<string, any>>} the written item, with `exp` set
322
+ */
323
+ async function putTransient(doc, tableName, item, ttlSeconds, now = nowSeconds, opts = {}) {
324
+ if (!ttlSeconds || ttlSeconds <= 0) {
325
+ throw new Error('putTransient: ttlSeconds must be a positive number')
326
+ }
327
+ const withExp = { ...item, exp: now() + ttlSeconds }
328
+ await doc.send(new PutCommand({ TableName: tableName, Item: withExp, ...opts }))
329
+ return withExp
330
+ }
331
+
332
+ module.exports = { ITEM, LOGIN_METHODS, HOOK_PAYLOAD_KINDS, keys, isDurableItem, isHookPayloadKey, putDurable, putTransient, nowSeconds }