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,720 @@
1
+ // The lifecycle hook contract: the version-1 event envelope and per-point payloads sent to an HTTPS or Lambda hook,
2
+ // validation of the declarative reply, and the schema of the runtime `hooks` config slice.
3
+ const { generateTypeId, isTypeId } = require('../../ids')
4
+ const { isReserved } = require('../identity/attribute-registry')
5
+ const { parseProviderIdentity } = require('../identity/stitch-provider')
6
+ const { getRequiredTokens, TOKEN_REGISTRY } = require('../cognito/emails/token-registry')
7
+ const { hasToken } = require('../email/validate')
8
+ const { assertSafeWebhookUrl } = require('./safe-webhook')
9
+
10
+ const ENVELOPE_VERSION = 1
11
+ const SERVICE = 'user-service'
12
+ const EVENT_ID_PREFIX = 'hk'
13
+
14
+ /** Event type sent for each hook point. */
15
+ const EVENT_TYPES = {
16
+ beforeSignUp: 'user.before_sign_up',
17
+ afterUserCreated: 'user.created',
18
+ beforeTokenIssue: 'token.before_issue',
19
+ afterSignIn: 'user.signed_in',
20
+ message: 'message.render',
21
+ }
22
+ /**
23
+ * The SSO lifecycle events of the ssoLifecycle point (src/sso/lifecycle-events.js): each says that one committed SSO change
24
+ * happened and names ids only, so a customer backend re-reads what it needs (POST /api/auth/status stays the truth).
25
+ */
26
+ const SSO_EVENT_TYPES = [
27
+ 'sso.user.deactivated',
28
+ 'sso.user.reactivated',
29
+ 'sso.user.deleted',
30
+ 'sso.groups.changed',
31
+ 'sso.connection.activated',
32
+ 'sso.connection.disabled',
33
+ 'sso.connection.deleted',
34
+ 'sso.enforcement.cutover',
35
+ 'sso.certificate.expiring',
36
+ 'sso.domain.unverified',
37
+ ]
38
+ /** The event types each point sends: one per point, except ssoLifecycle, which sends every SSO lifecycle event. */
39
+ /** @type {Record<string, string[]>} */
40
+ const POINT_EVENT_TYPES = {
41
+ ...Object.fromEntries(Object.entries(EVENT_TYPES).map(([point, type]) => [point, [type]])),
42
+ ssoLifecycle: SSO_EVENT_TYPES,
43
+ }
44
+ const HOOK_POINTS = Object.keys(POINT_EVENT_TYPES)
45
+
46
+ const METHODS = ['password', 'social', 'phone', 'invitation', 'passkey', 'magic-link']
47
+ const CREATED_VIA = ['sign-up', 'federated', 'invitation', 'admin', 'import']
48
+ const TOKEN_TRIGGERS = ['sign-in', 'refresh', 'new-password']
49
+ const PROVENANCES = ['server', 'client-metadata']
50
+ const EMAIL_SENDING_ACCOUNTS = ['COGNITO_DEFAULT', 'DEVELOPER']
51
+
52
+ // A reply larger than this is a failure, counted in bytes as received.
53
+ const MAX_REPLY_BYTES = 16 * 1024
54
+ // Serialized UTF-8 size of the whole claims object.
55
+ const MAX_CLAIMS_BYTES = 2048
56
+ const MAX_DENY_MESSAGE_CHARS = 200
57
+ // Cognito's limit for one custom attribute value.
58
+ const MAX_ATTRIBUTE_VALUE_CHARS = 2048
59
+ const MAX_ATTRIBUTES = 25
60
+ const MAX_IGNORED_NAMES = 20
61
+ const MAX_IGNORED_NAME_CHARS = 64
62
+ const MAX_GRANTS = 50
63
+ const DEFAULT_CLAIMS_TTL_SECONDS = 300
64
+ const MAX_CLAIMS_TTL_SECONDS = 3600
65
+
66
+ /**
67
+ * Per-point delivery rules. `timeoutRange` and `onFailure` exist only where the owner may choose them.
68
+ * @type {Record<string, { timeoutMs: number, timeoutRange?: [number, number], onFailure?: 'allow'|'deny' }>}
69
+ */
70
+ const POINT_RULES = {
71
+ beforeSignUp: { timeoutMs: 3000, timeoutRange: [1000, 3000], onFailure: 'deny' },
72
+ afterUserCreated: { timeoutMs: 10000 },
73
+ beforeTokenIssue: { timeoutMs: 1000, timeoutRange: [200, 2000], onFailure: 'allow' },
74
+ afterSignIn: { timeoutMs: 5000 },
75
+ message: { timeoutMs: 3000 },
76
+ ssoLifecycle: { timeoutMs: 10000 },
77
+ }
78
+
79
+ // Superseded hook keys and the points that replace them: a write naming one is refused with its replacement.
80
+ /** @type {Record<string, string>} */
81
+ const SUPERSEDED_KEYS = { postConfirmation: 'afterUserCreated', customMessage: 'message' }
82
+
83
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
84
+ function isPlainObject(value) {
85
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
86
+ }
87
+
88
+ /** @param {unknown} value @returns {value is string} */
89
+ function isNonEmptyString(value) {
90
+ return typeof value === 'string' && value.length > 0
91
+ }
92
+
93
+ /** @param {unknown} value @returns {boolean} true for an ISO-8601 instant */
94
+ function isInstant(value) {
95
+ return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(value) && !Number.isNaN(Date.parse(value))
96
+ }
97
+
98
+ // ---- envelope ----
99
+
100
+ /**
101
+ * @typedef {'beforeSignUp'|'afterUserCreated'|'beforeTokenIssue'|'afterSignIn'|'message'|'ssoLifecycle'} HookPoint
102
+ * @typedef {{ ip?: string, userAgent?: string, locale?: string, provenance: 'server'|'client-metadata' }} HookRequestContext
103
+ * @typedef {{ email?: string, phoneNumber?: string, method: string, provider?: string, invitationOrg?: string, request?: HookRequestContext }} BeforeSignUpData
104
+ * @typedef {{ suid: string, email?: string, phoneNumber?: string, emailVerified: boolean, method: string, provider?: string,
105
+ * createdVia: 'sign-up'|'federated'|'invitation'|'admin'|'import', personalOrgId?: string, invitationOrgId?: string }} UserCreatedData
106
+ * @typedef {{ suid: string, orgId?: string, loginMethod: string, trigger: 'sign-in'|'refresh'|'new-password' }} BeforeTokenIssueData
107
+ * @typedef {{ suid: string, orgId?: string, method: string, provider?: string, at: string, request?: HookRequestContext }} SignedInData
108
+ * @typedef {{ triggerSource: string, locale?: string, emailSendingAccount?: 'COGNITO_DEFAULT'|'DEVELOPER' }} MessageRenderData
109
+ * @typedef {{ connectionId: string, suid?: string }} SsoLifecycleData
110
+ * @typedef {{ type: string, version: 1, id: string, deploymentId: string, service: 'user-service', occurredAt: string,
111
+ * data: Record<string, unknown>, test?: true }} HookEnvelope
112
+ */
113
+
114
+ /** @typedef {{ required?: boolean, check: (value: unknown) => boolean, build?: (value: unknown, path: string) => unknown }} FieldRule */
115
+
116
+ const text = { check: isNonEmptyString }
117
+ const requiredText = { required: true, check: isNonEmptyString }
118
+ /** @param {string[]} values @param {boolean} [required] @returns {FieldRule} */
119
+ const oneOf = (values, required = false) => ({ required, check: (value) => typeof value === 'string' && values.includes(value) })
120
+
121
+ /** A list of placeholder names (may be empty). @type {FieldRule} */
122
+ const tokenList = { required: true, check: (value) => Array.isArray(value) && value.every(isNonEmptyString) }
123
+
124
+ /** @type {Record<string, FieldRule>} */
125
+ const REQUEST_FIELDS = {
126
+ ip: text,
127
+ userAgent: text,
128
+ locale: text,
129
+ provenance: oneOf(PROVENANCES, true),
130
+ }
131
+
132
+ /** @type {FieldRule} */
133
+ const requestContext = {
134
+ check: isPlainObject,
135
+ build: (value, path) => {
136
+ const request = buildFields(REQUEST_FIELDS, value, path)
137
+ if (Object.keys(request).length < 2) throw new Error(`${path} carries no context: omit it`)
138
+ return request
139
+ },
140
+ }
141
+
142
+ /** Every field a point's `data` may carry. Anything else is refused, so a token or secret cannot ride along. */
143
+ /** @type {Record<string, Record<string, FieldRule>>} */
144
+ const DATA_FIELDS = {
145
+ beforeSignUp: {
146
+ email: text,
147
+ phoneNumber: text,
148
+ method: oneOf(METHODS, true),
149
+ provider: text,
150
+ invitationOrg: text,
151
+ request: requestContext,
152
+ },
153
+ afterUserCreated: {
154
+ suid: requiredText,
155
+ email: text,
156
+ phoneNumber: text,
157
+ emailVerified: { required: true, check: (value) => typeof value === 'boolean' },
158
+ method: oneOf(METHODS, true),
159
+ provider: text,
160
+ createdVia: oneOf(CREATED_VIA, true),
161
+ personalOrgId: text,
162
+ invitationOrgId: text,
163
+ },
164
+ beforeTokenIssue: {
165
+ suid: requiredText,
166
+ orgId: text,
167
+ loginMethod: oneOf(METHODS, true),
168
+ trigger: oneOf(TOKEN_TRIGGERS, true),
169
+ },
170
+ afterSignIn: {
171
+ suid: requiredText,
172
+ orgId: text,
173
+ method: oneOf(METHODS, true),
174
+ provider: text,
175
+ at: { required: true, check: isInstant },
176
+ request: requestContext,
177
+ },
178
+ message: {
179
+ triggerSource: requiredText,
180
+ locale: text,
181
+ emailSendingAccount: oneOf(EMAIL_SENDING_ACCOUNTS),
182
+ requiredTokens: tokenList,
183
+ optionalTokens: tokenList,
184
+ },
185
+ // Ids only: the connection, and the person for a person's event. No address, user name, directory id or group name.
186
+ ssoLifecycle: {
187
+ connectionId: requiredText,
188
+ suid: text,
189
+ },
190
+ }
191
+
192
+ /**
193
+ * Copy the declared fields of `value` in declaration order, dropping undefined ones. Errors name the field, never its value.
194
+ * @param {Record<string, FieldRule>} fields
195
+ * @param {unknown} value
196
+ * @param {string} path
197
+ * @returns {Record<string, unknown>}
198
+ */
199
+ function buildFields(fields, value, path) {
200
+ if (!isPlainObject(value)) throw new Error(`${path} must be an object`)
201
+ for (const name of Object.keys(value)) {
202
+ if (!fields[name] && value[name] !== undefined) throw new Error(`${path}.${name} is not part of the hook contract`)
203
+ }
204
+ /** @type {Record<string, unknown>} */
205
+ const out = {}
206
+ for (const [name, rule] of Object.entries(fields)) {
207
+ const fieldValue = value[name]
208
+ if (fieldValue === undefined || fieldValue === null) {
209
+ if (rule.required) throw new Error(`${path}.${name} is required`)
210
+ continue
211
+ }
212
+ if (!rule.check(fieldValue)) throw new Error(`${path}.${name} is invalid`)
213
+ out[name] = rule.build ? rule.build(fieldValue, `${path}.${name}`) : fieldValue
214
+ }
215
+ return out
216
+ }
217
+
218
+ /** @param {string} point */
219
+ function assertPoint(point) {
220
+ if (!HOOK_POINTS.includes(point)) throw new Error(`unknown hook point: ${String(point).slice(0, MAX_IGNORED_NAME_CHARS)}`)
221
+ }
222
+
223
+ /** @returns {string} a new event id, reused as the `webhook-id` of every delivery attempt */
224
+ function newHookEventId() {
225
+ return generateTypeId(EVENT_ID_PREFIX)
226
+ }
227
+
228
+ /**
229
+ * The event type an envelope of `point` carries: the point's own, or for ssoLifecycle the SSO event named by `type`.
230
+ * @param {string} point @param {string|undefined} type
231
+ */
232
+ function eventTypeOf(point, type) {
233
+ const types = POINT_EVENT_TYPES[point]
234
+ if (type === undefined && types.length === 1) return types[0]
235
+ if (typeof type !== 'string' || !types.includes(type)) throw new Error(`hook envelope event type is not one ${point} sends`)
236
+ return type
237
+ }
238
+
239
+ /**
240
+ * Build the version-1 envelope for a point. The result holds only contract fields in a fixed order, so serializing
241
+ * it once gives the bytes every attempt of an async event sends.
242
+ * @param {{ point: string, type?: string, id: string, deploymentId: string, occurredAt: string, data: Record<string, unknown>, test?: boolean }} input
243
+ * type = the event type, required for ssoLifecycle (one of SSO_EVENT_TYPES)
244
+ * @returns {HookEnvelope}
245
+ */
246
+ function buildEnvelope({ point, type, id, deploymentId, occurredAt, data, test }) {
247
+ assertPoint(point)
248
+ const eventType = eventTypeOf(point, type)
249
+ if (!isTypeId(id, [EVENT_ID_PREFIX])) throw new Error('hook envelope id must be an hk_ id')
250
+ if (!isNonEmptyString(deploymentId)) throw new Error('hook envelope deploymentId is required')
251
+ if (!isInstant(occurredAt)) throw new Error('hook envelope occurredAt must be an ISO-8601 UTC instant')
252
+ /** @type {HookEnvelope} */
253
+ const envelope = {
254
+ type: eventType,
255
+ version: ENVELOPE_VERSION,
256
+ id,
257
+ deploymentId,
258
+ service: SERVICE,
259
+ occurredAt,
260
+ data: buildFields(DATA_FIELDS[point], data, 'data'),
261
+ }
262
+ if (test === true) envelope.test = true
263
+ return envelope
264
+ }
265
+
266
+ // ---- payloads from Cognito trigger events ----
267
+
268
+ /**
269
+ * `user.before_sign_up` data from a Cognito PreSignUp event. Cognito gives PreSignUp no IP, user agent or locale, so
270
+ * `request` appears only when the caller holds real context and states its provenance.
271
+ * @param {{ triggerSource?: string, userName?: string, request?: { userAttributes?: Record<string, string> } }} event
272
+ * @param {{ method?: string, invitationOrg?: string, request?: HookRequestContext }} [resolved]
273
+ * @returns {Record<string, unknown>}
274
+ */
275
+ function beforeSignUpData(event, resolved = {}) {
276
+ const attrs = (event.request && event.request.userAttributes) || {}
277
+ const external = event.triggerSource === 'PreSignUp_ExternalProvider'
278
+ const identity = external ? parseProviderIdentity(String(event.userName || '')) : null
279
+ return buildFields(DATA_FIELDS.beforeSignUp, {
280
+ email: attrs.email,
281
+ phoneNumber: attrs.phone_number,
282
+ method: resolved.method || (external ? 'social' : 'password'),
283
+ provider: identity ? identity.providerName : undefined,
284
+ invitationOrg: resolved.invitationOrg,
285
+ request: resolved.request,
286
+ }, 'data')
287
+ }
288
+
289
+ /** How an admission's `via` maps to `user.created` createdVia; a federated first sign-in is told apart by its provider. */
290
+ /** @type {Record<string, string>} */
291
+ const CREATED_VIA_BY_ADMISSION = {
292
+ confirmation: 'sign-up',
293
+ 'self-signup': 'sign-up',
294
+ invitation: 'invitation',
295
+ 'users-create': 'admin',
296
+ 'password-initialization': 'admin',
297
+ 'deployment-bootstrap': 'admin',
298
+ 'management-bootstrap': 'admin',
299
+ provisioned: 'admin',
300
+ adopted: 'import',
301
+ }
302
+
303
+ /**
304
+ * `user.created` data for an admitted account, from its PROFILE (whose email is set only once verified), its admission
305
+ * `via` and onboarding outcome, and the inviting org of an invitation registration.
306
+ * @param {{ suid: string, via: string, onboarding?: string, profile: Record<string, any>, invitationOrgId?: string }} input
307
+ * @returns {Record<string, unknown>}
308
+ */
309
+ function userCreatedData({ suid, via, onboarding, profile, invitationOrgId }) {
310
+ const providers = [...((profile && profile.providers) || [])]
311
+ const provider = providers.length ? String(providers[0]).split('#')[0] : undefined
312
+ const email = (profile && profile.email) || undefined
313
+ let createdVia = CREATED_VIA_BY_ADMISSION[via] || 'admin'
314
+ if (createdVia === 'sign-up' && provider) createdVia = 'federated'
315
+ const method = createdVia === 'invitation' ? 'invitation' : provider ? 'social' : email ? 'password' : 'phone'
316
+ return buildFields(DATA_FIELDS.afterUserCreated, {
317
+ suid,
318
+ email,
319
+ emailVerified: Boolean(email),
320
+ method,
321
+ provider,
322
+ createdVia,
323
+ personalOrgId: onboarding === 'personalOwner' && profile ? profile.orgId : undefined,
324
+ invitationOrgId: createdVia === 'invitation' ? invitationOrgId : undefined,
325
+ }, 'data')
326
+ }
327
+
328
+ /**
329
+ * `user.signed_in` data from a recorded sign-in event (who, how, and the default org at issuance).
330
+ * @param {{ suid: string, method: string, provider?: string, orgId?: string, occurredAt: string }} event
331
+ * @returns {Record<string, unknown>}
332
+ */
333
+ function signedInData(event) {
334
+ return buildFields(DATA_FIELDS.afterSignIn, { suid: event.suid, orgId: event.orgId, method: event.method, provider: event.provider, at: event.occurredAt }, 'data')
335
+ }
336
+
337
+ /** @type {Record<string, string>} */
338
+ const TOKEN_TRIGGER_BY_SOURCE = {
339
+ TokenGeneration_Authentication: 'sign-in',
340
+ TokenGeneration_HostedAuth: 'sign-in',
341
+ TokenGeneration_AuthenticateDevice: 'sign-in',
342
+ TokenGeneration_NewPasswordChallenge: 'new-password',
343
+ TokenGeneration_RefreshTokens: 'refresh',
344
+ }
345
+
346
+ /**
347
+ * Whether token.before_issue runs for a PreTokenGeneration trigger source (sign-in, new password, refresh).
348
+ * @param {unknown} triggerSource
349
+ * @returns {boolean}
350
+ */
351
+ function isTokenIssueSource(triggerSource) {
352
+ return Object.prototype.hasOwnProperty.call(TOKEN_TRIGGER_BY_SOURCE, String(triggerSource))
353
+ }
354
+
355
+ /**
356
+ * `token.before_issue` data from a Cognito PreTokenGeneration event. `orgId` is the server-owned default org and is
357
+ * absent until bootstrap has set one.
358
+ * @param {{ triggerSource?: string, request?: { userAttributes?: Record<string, string> } }} event
359
+ * @param {{ loginMethod: string }} resolved
360
+ * @returns {Record<string, unknown>}
361
+ */
362
+ function beforeTokenIssueData(event, resolved) {
363
+ const trigger = TOKEN_TRIGGER_BY_SOURCE[String(event.triggerSource)]
364
+ if (!trigger) throw new Error('token.before_issue does not run for this trigger source')
365
+ const attrs = (event.request && event.request.userAttributes) || {}
366
+ return buildFields(DATA_FIELDS.beforeTokenIssue, {
367
+ suid: attrs['custom:suid'],
368
+ orgId: attrs['custom:soid'] || undefined,
369
+ loginMethod: resolved.loginMethod,
370
+ trigger,
371
+ }, 'data')
372
+ }
373
+
374
+ /**
375
+ * `message.render` data from a Cognito CustomMessage event.
376
+ * @param {{ triggerSource?: string, request?: { userAttributes?: Record<string, string> } }} event
377
+ * @param {{ emailSendingAccount?: string }} [resolved]
378
+ * @returns {Record<string, unknown>}
379
+ */
380
+ function messageRenderData(event, resolved = {}) {
381
+ const attrs = (event.request && event.request.userAttributes) || {}
382
+ return buildFields(DATA_FIELDS.message, {
383
+ triggerSource: event.triggerSource,
384
+ locale: attrs.locale || undefined,
385
+ emailSendingAccount: resolved.emailSendingAccount,
386
+ // The placeholders a returned body must keep, and the others it may use.
387
+ requiredTokens: getRequiredTokens(event.triggerSource),
388
+ optionalTokens: TOKEN_REGISTRY[event.triggerSource] ? TOKEN_REGISTRY[event.triggerSource].optional.slice() : [],
389
+ }, 'data')
390
+ }
391
+
392
+ // ---- replies ----
393
+
394
+ const ACTION_FIELDS = ['allow', 'message', 'attributes', 'memberships', 'defaultOrg', 'claims']
395
+ const MESSAGE_FIELDS = ['subject', 'html', 'text', 'template']
396
+ // The reply fields carrying a message body, which must keep the trigger's required placeholders.
397
+ const MESSAGE_BODY_FIELDS = ['html', 'text', 'template']
398
+
399
+ // What a hook may never do at any point: mark an account or its contact verified or confirmed. Refused, not ignored,
400
+ // so a receiver relying on it learns at once.
401
+ const NEVER_SUPPORTED = ['autoVerify', 'autoConfirm']
402
+
403
+ /** Reply fields each point accepts. A known action field outside its point is refused. */
404
+ /** @type {Record<string, string[]>} */
405
+ const POINT_ACTIONS = {
406
+ beforeSignUp: ['allow', 'message'],
407
+ afterUserCreated: ['attributes', 'memberships', 'defaultOrg'],
408
+ beforeTokenIssue: ['claims'],
409
+ afterSignIn: [],
410
+ message: MESSAGE_FIELDS,
411
+ ssoLifecycle: [],
412
+ }
413
+
414
+ /**
415
+ * @typedef {{ org: string, role: string }} HookGrant
416
+ * @typedef {{ grants?: HookGrant[], emailSendingAccount?: string, triggerSource?: string }} ReplyContext
417
+ * @typedef {{ ok: true, actions: Record<string, unknown>, ignored: string[] }} AcceptedReply
418
+ * @typedef {{ ok: false, reason: string, fields: string[] }} RefusedReply
419
+ */
420
+
421
+ /** @param {string} reason @param {string[]} [fields] @returns {RefusedReply} */
422
+ function refuse(reason, fields = []) {
423
+ return { ok: false, reason, fields: fields.map(boundName) }
424
+ }
425
+
426
+ /** @param {string} name */
427
+ function boundName(name) {
428
+ return name.slice(0, MAX_IGNORED_NAME_CHARS)
429
+ }
430
+
431
+ /** @param {HookGrant[]} grants @param {unknown} org @param {unknown} role */
432
+ function isGranted(grants, org, role) {
433
+ return grants.some((grant) => grant.org === org && grant.role === role)
434
+ }
435
+
436
+ /**
437
+ * Decode a reply body to a JSON object. An empty body is `null` (the point decides whether that is acceptable).
438
+ * @param {Buffer|Uint8Array|string|undefined|null} body
439
+ * @returns {{ reply: Record<string, unknown>|null }|RefusedReply}
440
+ */
441
+ function decodeReply(body) {
442
+ if (body === undefined || body === null) return { reply: null }
443
+ const raw = typeof body === 'string' ? Buffer.from(body, 'utf8') : Buffer.from(body)
444
+ if (raw.length > MAX_REPLY_BYTES) return refuse('reply_too_large')
445
+ let decoded
446
+ try { decoded = new TextDecoder('utf-8', { fatal: true }).decode(raw) } catch { return refuse('reply_not_utf8') }
447
+ if (!decoded.trim()) return { reply: null }
448
+ let parsed
449
+ try { parsed = JSON.parse(decoded) } catch { return refuse('reply_not_json') }
450
+ if (!isPlainObject(parsed)) return refuse('reply_not_object')
451
+ return { reply: parsed }
452
+ }
453
+
454
+ /** @param {unknown} value @returns {Record<string, string>|RefusedReply} */
455
+ function attributesAction(value) {
456
+ if (!isPlainObject(value)) return refuse('invalid_action', ['attributes'])
457
+ const names = Object.keys(value)
458
+ const reserved = names.filter((name) => !name.startsWith('custom:') || isReserved(name))
459
+ if (reserved.length) return refuse('reserved_field', reserved)
460
+ if (names.length > MAX_ATTRIBUTES) return refuse('invalid_action', ['attributes'])
461
+ /** @type {Record<string, string>} */
462
+ const out = {}
463
+ for (const name of names) {
464
+ const attr = value[name]
465
+ if (!['string', 'number', 'boolean'].includes(typeof attr)) return refuse('invalid_action', ['attributes'])
466
+ const asText = String(attr)
467
+ if (asText.length > MAX_ATTRIBUTE_VALUE_CHARS) return refuse('invalid_action', ['attributes'])
468
+ out[name] = asText
469
+ }
470
+ return out
471
+ }
472
+
473
+ /** @param {unknown} value @param {HookGrant[]} grants @returns {HookGrant[]|RefusedReply} */
474
+ function membershipsAction(value, grants) {
475
+ if (!Array.isArray(value)) return refuse('invalid_action', ['memberships'])
476
+ /** @type {HookGrant[]} */
477
+ const out = []
478
+ for (const entry of value) {
479
+ if (!isPlainObject(entry) || !isNonEmptyString(entry.org) || !isNonEmptyString(entry.role)) return refuse('invalid_action', ['memberships'])
480
+ if (!isGranted(grants, entry.org, entry.role)) return refuse('membership_not_granted', ['memberships'])
481
+ if (!isGranted(out, entry.org, entry.role)) out.push({ org: entry.org, role: entry.role })
482
+ }
483
+ return out
484
+ }
485
+
486
+ /** @param {unknown} value @returns {Record<string, string|number|boolean>|RefusedReply} */
487
+ function claimsAction(value) {
488
+ if (!isPlainObject(value)) return refuse('invalid_action', ['claims'])
489
+ const names = Object.keys(value)
490
+ const reserved = names.filter((name) => !/^app:[A-Za-z0-9_.-]+$/.test(name) || isReserved(name))
491
+ if (reserved.length) return refuse('reserved_field', reserved)
492
+ for (const name of names) {
493
+ const claim = value[name]
494
+ const scalar = typeof claim === 'string' || typeof claim === 'boolean' || (typeof claim === 'number' && Number.isFinite(claim))
495
+ if (!scalar) return refuse('invalid_action', ['claims'])
496
+ }
497
+ if (Buffer.byteLength(JSON.stringify(value), 'utf8') > MAX_CLAIMS_BYTES) return refuse('claims_too_large', ['claims'])
498
+ return /** @type {Record<string, string|number|boolean>} */ ({ ...value })
499
+ }
500
+
501
+ /** @param {unknown} value @returns {boolean} plain text within the deny-message limit */
502
+ function isDenyMessage(value) {
503
+ // eslint-disable-next-line no-control-regex
504
+ return typeof value === 'string' && Array.from(value).length <= MAX_DENY_MESSAGE_CHARS && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value)
505
+ }
506
+
507
+ /**
508
+ * Validate a hook's reply for a point and reduce it to the actions user-service may apply. A refusal is a hook
509
+ * failure handled by the point's failure policy; it names fields only, never returned values.
510
+ * @param {string} point
511
+ * @param {Buffer|Uint8Array|string|undefined|null} body the reply exactly as received
512
+ * @param {ReplyContext} [ctx]
513
+ * @returns {AcceptedReply|RefusedReply}
514
+ */
515
+ function parseHookReply(point, body, ctx = {}) {
516
+ assertPoint(point)
517
+ // Notification only: nothing in the body is acted on.
518
+ if (point === 'afterSignIn' || point === 'ssoLifecycle') return { ok: true, actions: {}, ignored: [] }
519
+
520
+ const decoded = decodeReply(body)
521
+ if ('ok' in decoded) return decoded
522
+ const reply = decoded.reply || {}
523
+ const allowed = POINT_ACTIONS[point]
524
+ const names = Object.keys(reply)
525
+
526
+ const unsupported = names.filter((name) => NEVER_SUPPORTED.includes(name) || ((ACTION_FIELDS.includes(name) || MESSAGE_FIELDS.includes(name)) && !allowed.includes(name)))
527
+ if (unsupported.length) return refuse('unsupported_action', unsupported)
528
+ const ignored = names.filter((name) => !allowed.includes(name)).slice(0, MAX_IGNORED_NAMES).map(boundName)
529
+
530
+ /** @type {Record<string, unknown>} */
531
+ const actions = {}
532
+ const grants = Array.isArray(ctx.grants) ? ctx.grants : []
533
+
534
+ if (point === 'beforeSignUp') {
535
+ if (typeof reply.allow !== 'boolean') return refuse('allow_required', ['allow'])
536
+ actions.allow = reply.allow
537
+ if (reply.message !== undefined) {
538
+ if (!isDenyMessage(reply.message)) return refuse('invalid_action', ['message'])
539
+ actions.message = reply.message
540
+ }
541
+ return { ok: true, actions, ignored }
542
+ }
543
+
544
+ if (point === 'afterUserCreated') {
545
+ if (reply.attributes !== undefined) {
546
+ const attributes = attributesAction(reply.attributes)
547
+ if (attributes.ok === false) return /** @type {RefusedReply} */ (attributes)
548
+ actions.attributes = attributes
549
+ }
550
+ if (reply.memberships !== undefined) {
551
+ const memberships = membershipsAction(reply.memberships, grants)
552
+ if (!Array.isArray(memberships)) return memberships
553
+ actions.memberships = memberships
554
+ }
555
+ if (reply.defaultOrg !== undefined) {
556
+ if (!isNonEmptyString(reply.defaultOrg)) return refuse('invalid_action', ['defaultOrg'])
557
+ if (reply.defaultOrg !== 'personal' && !grants.some((grant) => grant.org === reply.defaultOrg)) return refuse('default_org_not_granted', ['defaultOrg'])
558
+ actions.defaultOrg = reply.defaultOrg
559
+ }
560
+ return { ok: true, actions, ignored }
561
+ }
562
+
563
+ if (point === 'beforeTokenIssue') {
564
+ if (reply.claims !== undefined) {
565
+ const claims = claimsAction(reply.claims)
566
+ if (claims.ok === false) return /** @type {RefusedReply} */ (claims)
567
+ actions.claims = claims
568
+ }
569
+ return { ok: true, actions, ignored }
570
+ }
571
+
572
+ // message
573
+ const present = MESSAGE_FIELDS.filter((name) => reply[name] !== undefined)
574
+ const mistyped = present.filter((name) => typeof reply[name] !== 'string')
575
+ if (mistyped.length) return refuse('invalid_action', mistyped)
576
+ const required = ctx.triggerSource ? getRequiredTokens(ctx.triggerSource) : []
577
+ const incomplete = present.filter((name) => MESSAGE_BODY_FIELDS.includes(name) && required.some((token) => !hasToken(reply[name], token)))
578
+ if (incomplete.length) return refuse('placeholder_missing', incomplete)
579
+ for (const name of present) actions[name] = reply[name]
580
+ return { ok: true, actions, ignored }
581
+ }
582
+
583
+ // ---- runtime config ----
584
+
585
+ const TARGET_KEYS = ['url', 'lambdaArn']
586
+ const LAMBDA_ARN = /^arn:[^:]+:lambda:[^:]+:\d{12}:function:[A-Za-z0-9_-]+(?::[A-Za-z0-9$_-]+)?$/
587
+ const GRANT_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/
588
+
589
+ /** @param {string} message @returns {Error & { code: string }} */
590
+ function configInvalid(message) {
591
+ return Object.assign(new Error(`config.hooks${message}`), { code: 'CONFIG_INVALID' })
592
+ }
593
+
594
+ /**
595
+ * @param {string} point
596
+ * @param {unknown} entry
597
+ * @param {string[]} allowedLambdaArns
598
+ */
599
+ function validatePointConfig(point, entry, allowedLambdaArns) {
600
+ const rules = POINT_RULES[point]
601
+ if (!isPlainObject(entry)) throw configInvalid(`.${point} must be an object naming a url or a lambdaArn`)
602
+ const allowed = [...TARGET_KEYS, 'onFailure', 'timeoutMs', 'claimsTtlSeconds']
603
+ const unknown = Object.keys(entry).filter((key) => !allowed.includes(key))
604
+ if (unknown.length) throw configInvalid(`.${point} has unsupported settings: ${unknown.map(boundName).join(', ')}`)
605
+
606
+ const targets = TARGET_KEYS.filter((key) => entry[key] !== undefined)
607
+ if (targets.length !== 1) throw configInvalid(`.${point} must name exactly one target: url or lambdaArn`)
608
+ if (entry.url !== undefined) {
609
+ try {
610
+ if (typeof entry.url !== 'string') throw new Error('webhook URL is invalid')
611
+ assertSafeWebhookUrl(entry.url)
612
+ } catch (err) {
613
+ throw configInvalid(`.${point}.url is not allowed: ${/** @type {Error} */ (err).message}`)
614
+ }
615
+ } else {
616
+ if (typeof entry.lambdaArn !== 'string' || !LAMBDA_ARN.test(entry.lambdaArn)) throw configInvalid(`.${point}.lambdaArn must be a full Lambda ARN`)
617
+ if (!allowedLambdaArns.includes(entry.lambdaArn)) throw configInvalid(`.${point}.lambdaArn is not listed in the HookLambdaArns deployment setting`)
618
+ }
619
+
620
+ if (entry.onFailure !== undefined) {
621
+ if (!rules.onFailure) throw configInvalid(`.${point}.onFailure is not configurable for this point`)
622
+ if (entry.onFailure !== 'allow' && entry.onFailure !== 'deny') throw configInvalid(`.${point}.onFailure must be allow or deny`)
623
+ }
624
+ if (entry.timeoutMs !== undefined) {
625
+ if (!rules.timeoutRange) throw configInvalid(`.${point}.timeoutMs is not configurable for this point`)
626
+ const [min, max] = rules.timeoutRange
627
+ if (!Number.isInteger(entry.timeoutMs) || /** @type {number} */ (entry.timeoutMs) < min || /** @type {number} */ (entry.timeoutMs) > max) {
628
+ throw configInvalid(`.${point}.timeoutMs must be an integer from ${min} to ${max}`)
629
+ }
630
+ }
631
+ if (entry.claimsTtlSeconds !== undefined) {
632
+ if (point !== 'beforeTokenIssue') throw configInvalid(`.${point}.claimsTtlSeconds is only configurable for beforeTokenIssue`)
633
+ if (!Number.isInteger(entry.claimsTtlSeconds) || /** @type {number} */ (entry.claimsTtlSeconds) < 0 || /** @type {number} */ (entry.claimsTtlSeconds) > MAX_CLAIMS_TTL_SECONDS) {
634
+ throw configInvalid(`.${point}.claimsTtlSeconds must be an integer from 0 to ${MAX_CLAIMS_TTL_SECONDS}`)
635
+ }
636
+ }
637
+ }
638
+
639
+ /** @param {unknown} grants */
640
+ function validateGrants(grants) {
641
+ if (!Array.isArray(grants)) throw configInvalid('.grants must be a list of { org, role } pairs')
642
+ if (grants.length > MAX_GRANTS) throw configInvalid(`.grants lists more than ${MAX_GRANTS} pairs`)
643
+ /** @type {HookGrant[]} */
644
+ const seen = []
645
+ grants.forEach((grant, index) => {
646
+ if (!isPlainObject(grant) || Object.keys(grant).some((key) => key !== 'org' && key !== 'role')) {
647
+ throw configInvalid(`.grants[${index}] must be exactly { org, role }`)
648
+ }
649
+ for (const key of ['org', 'role']) {
650
+ const id = grant[key]
651
+ if (typeof id !== 'string' || !GRANT_ID.test(id)) throw configInvalid(`.grants[${index}].${key} must be an exact id`)
652
+ }
653
+ if (isGranted(seen, grant.org, grant.role)) throw configInvalid(`.grants[${index}] repeats an earlier pair`)
654
+ seen.push({ org: /** @type {string} */ (grant.org), role: /** @type {string} */ (grant.role) })
655
+ })
656
+ }
657
+
658
+ /**
659
+ * Validate the runtime `hooks` config slice. Absent hooks are valid (no hook runs).
660
+ * @param {unknown} hooks
661
+ * @param {{ allowedLambdaArns?: string[], ssoEnabled?: boolean }} [opts] allowedLambdaArns = the exact ARNs of the
662
+ * HookLambdaArns deployment setting; ssoEnabled = the instance's EnableSso (ssoLifecycle is refused without it)
663
+ * @returns {true} throws CONFIG_INVALID otherwise
664
+ */
665
+ function validateHooksConfig(hooks, opts = {}) {
666
+ if (hooks === undefined || hooks === null) return true
667
+ if (!isPlainObject(hooks)) throw configInvalid(' must be an object')
668
+ const allowedLambdaArns = Array.isArray(opts.allowedLambdaArns) ? opts.allowedLambdaArns : []
669
+ for (const [key, entry] of Object.entries(hooks)) {
670
+ if (Object.prototype.hasOwnProperty.call(SUPERSEDED_KEYS, key)) throw configInvalid(`.${key} is no longer supported; use hooks.${SUPERSEDED_KEYS[key]}`)
671
+ if (key === 'grants') validateGrants(entry)
672
+ else if (key === 'ssoLifecycle' && opts.ssoEnabled !== true) throw configInvalid('.ssoLifecycle needs SSO: EnableSso is off for this instance')
673
+ else if (HOOK_POINTS.includes(key)) validatePointConfig(key, entry, allowedLambdaArns)
674
+ else throw configInvalid(`.${boundName(key)} is not a hook point`)
675
+ }
676
+ return true
677
+ }
678
+
679
+ /**
680
+ * The effective settings of a configured point, or null when the point has no hook.
681
+ * @param {Record<string, any>|undefined|null} hooks a validated `hooks` config slice
682
+ * @param {string} point
683
+ * @returns {{ target: { kind: 'url', url: string }|{ kind: 'lambda', lambdaArn: string }, timeoutMs: number,
684
+ * onFailure?: 'allow'|'deny', claimsTtlSeconds?: number }|null}
685
+ */
686
+ function resolveHookPoint(hooks, point) {
687
+ assertPoint(point)
688
+ const entry = hooks && hooks[point]
689
+ if (!isPlainObject(entry)) return null
690
+ const rules = POINT_RULES[point]
691
+ /** @type {NonNullable<ReturnType<typeof resolveHookPoint>>} */
692
+ const resolved = {
693
+ target: typeof entry.url === 'string' ? { kind: 'url', url: entry.url } : { kind: 'lambda', lambdaArn: String(entry.lambdaArn) },
694
+ timeoutMs: typeof entry.timeoutMs === 'number' ? entry.timeoutMs : rules.timeoutMs,
695
+ }
696
+ if (rules.onFailure) resolved.onFailure = entry.onFailure === 'allow' || entry.onFailure === 'deny' ? entry.onFailure : rules.onFailure
697
+ if (point === 'beforeTokenIssue') resolved.claimsTtlSeconds = typeof entry.claimsTtlSeconds === 'number' ? entry.claimsTtlSeconds : DEFAULT_CLAIMS_TTL_SECONDS
698
+ return resolved
699
+ }
700
+
701
+ module.exports = {
702
+ HOOK_POINTS,
703
+ EVENT_TYPES,
704
+ SSO_EVENT_TYPES,
705
+ POINT_EVENT_TYPES,
706
+ ENVELOPE_VERSION,
707
+ MAX_REPLY_BYTES,
708
+ MAX_CLAIMS_BYTES,
709
+ newHookEventId,
710
+ buildEnvelope,
711
+ beforeSignUpData,
712
+ userCreatedData,
713
+ signedInData,
714
+ beforeTokenIssueData,
715
+ isTokenIssueSource,
716
+ messageRenderData,
717
+ parseHookReply,
718
+ validateHooksConfig,
719
+ resolveHookPoint,
720
+ }