@molecule/api-resource-user 1.4.13 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-10-15T23:29:57.665Z
6
+ Generated: 2026-10-16T04:11:24.716Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-user
@@ -81,12 +81,20 @@ interface UserRequestHandlerMap {
81
81
 
82
82
  ### Types
83
83
 
84
- #### `CreateOAuthProps`
84
+ #### `Props`
85
85
 
86
- Create O Auth Props type.
86
+ User props type inferred from schema.
87
87
 
88
88
  ```typescript
89
- type CreateOAuthProps = z.infer<typeof createOAuthPropsSchema>
89
+ type Props = z.infer<typeof propsSchema>
90
+ ```
91
+
92
+ #### `SecretProps`
93
+
94
+ Secret Props type.
95
+
96
+ ```typescript
97
+ type SecretProps = z.infer<typeof secretPropsSchema>
90
98
  ```
91
99
 
92
100
  #### `CreateProps`
@@ -105,28 +113,20 @@ Create Secret Props type.
105
113
  type CreateSecretProps = z.infer<typeof createSecretPropsSchema>
106
114
  ```
107
115
 
108
- #### `Props`
109
-
110
- User props type inferred from schema.
111
-
112
- ```typescript
113
- type Props = z.infer<typeof propsSchema>
114
- ```
115
-
116
- #### `SecretProps`
116
+ #### `CreateOAuthProps`
117
117
 
118
- Secret Props type.
118
+ Create O Auth Props type.
119
119
 
120
120
  ```typescript
121
- type SecretProps = z.infer<typeof secretPropsSchema>
121
+ type CreateOAuthProps = z.infer<typeof createOAuthPropsSchema>
122
122
  ```
123
123
 
124
- #### `Session`
124
+ #### `UpdateProps`
125
125
 
126
- User session data (userId, email, role, permissions, metadata) inferred from sessionSchema.
126
+ Update Props type.
127
127
 
128
128
  ```typescript
129
- type Session = z.infer<typeof sessionSchema>
129
+ type UpdateProps = z.infer<typeof updatePropsSchema>
130
130
  ```
131
131
 
132
132
  #### `UpdatePasswordSecretProps`
@@ -145,14 +145,6 @@ Update Plan Props type.
145
145
  type UpdatePlanProps = z.infer<typeof updatePlanPropsSchema>
146
146
  ```
147
147
 
148
- #### `UpdateProps`
149
-
150
- Update Props type.
151
-
152
- ```typescript
153
- type UpdateProps = z.infer<typeof updatePropsSchema>
154
- ```
155
-
156
148
  #### `VerifyTwoFactorProps`
157
149
 
158
150
  Verify Two Factor Props type.
@@ -169,6 +161,14 @@ Verify Two Factor Secret Props type.
169
161
  type VerifyTwoFactorSecretProps = z.infer<typeof verifyTwoFactorSecretPropsSchema>
170
162
  ```
171
163
 
164
+ #### `Session`
165
+
166
+ User session data (userId, email, role, permissions, metadata) inferred from sessionSchema.
167
+
168
+ ```typescript
169
+ type Session = z.infer<typeof sessionSchema>
170
+ ```
171
+
172
172
  ### Functions
173
173
 
174
174
  #### `createRequestHandlerMap(createRequestHandler)`
@@ -262,59 +262,46 @@ function createSchema(options?: { oauthServers?: OAuthServers; planKeys?: PlanKe
262
262
 
263
263
  ### Constants
264
264
 
265
- #### `createOAuthPropsSchema`
265
+ #### `i18nRegistered`
266
266
 
267
- Schema for creating a user via OAuth.
267
+ The i18n registered.
268
268
 
269
269
  ```typescript
270
- const createOAuthPropsSchema: z.ZodObject<
271
- {
272
- username: z.ZodOptional<z.ZodString>
273
- name: z.ZodOptional<z.ZodString>
274
- email: z.ZodOptional<z.ZodNullable<z.ZodString>>
275
- emailVerified: z.ZodOptional<z.ZodBoolean>
276
- avatar: z.ZodOptional<z.ZodNullable<z.ZodString>>
277
- bio: z.ZodOptional<z.ZodNullable<z.ZodString>>
278
- oauthServer: z.ZodOptional<z.ZodString> | z.ZodOptional<z.ZodEnum<{}>>
279
- oauthId: z.ZodOptional<z.ZodString>
280
- oauthData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>
281
- },
282
- z.core.$strip
283
- >
270
+ const i18nRegistered: true
284
271
  ```
285
272
 
286
- #### `createPropsSchema`
273
+ #### `resource`
287
274
 
288
- Schema for creating a user via password.
275
+ Default user resource definition.
289
276
 
290
277
  ```typescript
291
- const createPropsSchema: z.ZodObject<
292
- {
293
- username: z.ZodOptional<z.ZodString>
294
- name: z.ZodOptional<z.ZodString>
295
- email: z.ZodOptional<z.ZodNullable<z.ZodString>>
296
- },
297
- z.core.$strip
298
- >
278
+ const resource: types.Resource<unknown>
299
279
  ```
300
280
 
301
- #### `createSecretPropsSchema`
281
+ #### `routes`
302
282
 
303
- Schema for creating secret props (password hash only).
283
+ Route definitions for the User resource.
284
+ Routes marked optional require additional packages to be installed.
285
+
286
+ Declarative route definitions used by the injection engine.
304
287
 
305
288
  ```typescript
306
- const createSecretPropsSchema: z.ZodObject<
307
- { passwordHash: z.ZodOptional<z.ZodString> },
308
- z.core.$strip
309
- >
289
+ const routes: (
290
+ | { method: 'post'; path: string; middlewares: string[]; handler: string; optional?: undefined }
291
+ | { method: 'get'; path: string; middlewares: string[]; handler: string; optional: string }
292
+ | { method: 'post'; path: string; middlewares: string[]; handler: string; optional: string }
293
+ | { method: 'get'; path: string; middlewares: string[]; handler: string; optional?: undefined }
294
+ | { method: 'patch'; path: string; middlewares: string[]; handler: string; optional?: undefined }
295
+ | { method: 'delete'; path: string; middlewares: string[]; handler: string; optional?: undefined }
296
+ )[]
310
297
  ```
311
298
 
312
- #### `i18nRegistered`
299
+ #### `MAX_BIO_LENGTH`
313
300
 
314
- The i18n registered.
301
+ Maximum length (in characters) of a user's `bio`.
315
302
 
316
303
  ```typescript
317
- const i18nRegistered: true
304
+ const MAX_BIO_LENGTH: 1000
318
305
  ```
319
306
 
320
307
  #### `MAX_AVATAR_LENGTH`
@@ -327,14 +314,6 @@ Larger avatars must be hosted elsewhere and referenced by URL.
327
314
  const MAX_AVATAR_LENGTH: number
328
315
  ```
329
316
 
330
- #### `MAX_BIO_LENGTH`
331
-
332
- Maximum length (in characters) of a user's `bio`.
333
-
334
- ```typescript
335
- const MAX_BIO_LENGTH: 1000
336
- ```
337
-
338
317
  #### `propsSchema`
339
318
 
340
319
  Default schema for user props.
@@ -363,40 +342,6 @@ const propsSchema: z.ZodObject<
363
342
  >
364
343
  ```
365
344
 
366
- #### `resource`
367
-
368
- Default user resource definition.
369
-
370
- ```typescript
371
- const resource: types.Resource<unknown>
372
- ```
373
-
374
- #### `resourceUserSecretDefinitions`
375
-
376
- Secret definitions required by the user resource.
377
-
378
- ```typescript
379
- const resourceUserSecretDefinitions: SecretDefinition[]
380
- ```
381
-
382
- #### `routes`
383
-
384
- Route definitions for the User resource.
385
- Routes marked optional require additional packages to be installed.
386
-
387
- Declarative route definitions used by the injection engine.
388
-
389
- ```typescript
390
- const routes: (
391
- | { method: 'post'; path: string; middlewares: string[]; handler: string; optional?: undefined }
392
- | { method: 'get'; path: string; middlewares: string[]; handler: string; optional: string }
393
- | { method: 'post'; path: string; middlewares: string[]; handler: string; optional: string }
394
- | { method: 'get'; path: string; middlewares: string[]; handler: string; optional?: undefined }
395
- | { method: 'patch'; path: string; middlewares: string[]; handler: string; optional?: undefined }
396
- | { method: 'delete'; path: string; middlewares: string[]; handler: string; optional?: undefined }
397
- )[]
398
- ```
399
-
400
345
  #### `secretPropsSchema`
401
346
 
402
347
  Secret properties stored in a separate table.
@@ -416,44 +361,48 @@ const secretPropsSchema: z.ZodObject<
416
361
  >
417
362
  ```
418
363
 
419
- #### `sessionSchema`
364
+ #### `createPropsSchema`
420
365
 
421
- Zod schema for JWT session payloads (userId, deviceId, optional OAuth fields).
366
+ Schema for creating a user via password.
422
367
 
423
368
  ```typescript
424
- const sessionSchema: z.ZodObject<
369
+ const createPropsSchema: z.ZodObject<
425
370
  {
426
- id: z.ZodOptional<z.ZodString>
427
- userId: z.ZodString
428
- deviceId: z.ZodString
429
- oauthServer: z.ZodOptional<z.ZodString>
430
- oauthId: z.ZodOptional<z.ZodString>
371
+ username: z.ZodOptional<z.ZodString>
372
+ name: z.ZodOptional<z.ZodString>
373
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>
431
374
  },
432
375
  z.core.$strip
433
376
  >
434
377
  ```
435
378
 
436
- #### `updatePasswordSecretPropsSchema`
379
+ #### `createSecretPropsSchema`
437
380
 
438
- Schema for updating password secret props (partial password hash).
381
+ Schema for creating secret props (password hash only).
439
382
 
440
383
  ```typescript
441
- const updatePasswordSecretPropsSchema: z.ZodObject<
442
- { passwordHash: z.ZodOptional<z.ZodOptional<z.ZodString>> },
384
+ const createSecretPropsSchema: z.ZodObject<
385
+ { passwordHash: z.ZodOptional<z.ZodString> },
443
386
  z.core.$strip
444
387
  >
445
388
  ```
446
389
 
447
- #### `updatePlanPropsSchema`
390
+ #### `createOAuthPropsSchema`
448
391
 
449
- Schema for updating a user's plan (partial planKey, planExpiresAt, planAutoRenews).
392
+ Schema for creating a user via OAuth.
450
393
 
451
394
  ```typescript
452
- const updatePlanPropsSchema: z.ZodObject<
395
+ const createOAuthPropsSchema: z.ZodObject<
453
396
  {
454
- planKey: z.ZodOptional<z.ZodOptional<z.ZodString> | z.ZodOptional<z.ZodEnum<{}>>>
455
- planExpiresAt: z.ZodOptional<z.ZodOptional<z.ZodString>>
456
- planAutoRenews: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>
397
+ oauthServer: z.ZodOptional<z.ZodString> | z.ZodOptional<z.ZodEnum<{}>>
398
+ oauthId: z.ZodOptional<z.ZodString>
399
+ username: z.ZodOptional<z.ZodString>
400
+ name: z.ZodOptional<z.ZodString>
401
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>
402
+ emailVerified: z.ZodOptional<z.ZodBoolean>
403
+ avatar: z.ZodOptional<z.ZodNullable<z.ZodString>>
404
+ bio: z.ZodOptional<z.ZodNullable<z.ZodString>>
405
+ oauthData: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>
457
406
  },
458
407
  z.core.$strip
459
408
  >
@@ -476,6 +425,32 @@ const updatePropsSchema: z.ZodObject<
476
425
  >
477
426
  ```
478
427
 
428
+ #### `updatePasswordSecretPropsSchema`
429
+
430
+ Schema for updating password secret props (partial password hash).
431
+
432
+ ```typescript
433
+ const updatePasswordSecretPropsSchema: z.ZodObject<
434
+ { passwordHash: z.ZodOptional<z.ZodOptional<z.ZodString>> },
435
+ z.core.$strip
436
+ >
437
+ ```
438
+
439
+ #### `updatePlanPropsSchema`
440
+
441
+ Schema for updating a user's plan (partial planKey, planExpiresAt, planAutoRenews).
442
+
443
+ ```typescript
444
+ const updatePlanPropsSchema: z.ZodObject<
445
+ {
446
+ planKey: z.ZodOptional<z.ZodOptional<z.ZodString> | z.ZodOptional<z.ZodEnum<{}>>>
447
+ planExpiresAt: z.ZodOptional<z.ZodOptional<z.ZodString>>
448
+ planAutoRenews: z.ZodOptional<z.ZodOptional<z.ZodBoolean>>
449
+ },
450
+ z.core.$strip
451
+ >
452
+ ```
453
+
479
454
  #### `verifyTwoFactorPropsSchema`
480
455
 
481
456
  Schema for verifying two-factor authentication.
@@ -494,384 +469,1372 @@ Schema for two-factor secret props.
494
469
  ```typescript
495
470
  const verifyTwoFactorSecretPropsSchema: z.ZodObject<
496
471
  {
497
- pendingTwoFactorSecret: z.ZodOptional<z.ZodOptional<z.ZodString>>
498
472
  twoFactorSecret: z.ZodOptional<z.ZodOptional<z.ZodString>>
473
+ pendingTwoFactorSecret: z.ZodOptional<z.ZodOptional<z.ZodString>>
474
+ },
475
+ z.core.$strip
476
+ >
477
+ ```
478
+
479
+ #### `sessionSchema`
480
+
481
+ Zod schema for JWT session payloads (userId, deviceId, optional OAuth fields).
482
+
483
+ ```typescript
484
+ const sessionSchema: z.ZodObject<
485
+ {
486
+ id: z.ZodOptional<z.ZodString>
487
+ userId: z.ZodString
488
+ deviceId: z.ZodString
489
+ oauthServer: z.ZodOptional<z.ZodString>
490
+ oauthId: z.ZodOptional<z.ZodString>
499
491
  },
500
492
  z.core.$strip
501
493
  >
502
494
  ```
503
495
 
496
+ #### `resourceUserSecretDefinitions`
497
+
498
+ Secret definitions required by the user resource.
499
+
500
+ ```typescript
501
+ const resourceUserSecretDefinitions: SecretDefinition[]
502
+ ```
503
+
504
504
  ### Namespaces
505
505
 
506
+ #### `z`
507
+
508
+ Re-exports the `zod` module — `z.<name>` is exactly `zod.<name>`, documented by that package (installed at `node_modules/zod`).
509
+
506
510
  #### `authorization`
507
511
 
508
- Members:
512
+ Re-exported as a namespace — reach every member below through it (e.g. `authorization.<name>`).
509
513
 
510
- - `authorization.getAuthCookieName` — function: Resolve the actual cookie name for an auth cookie.
511
- - `authorization.getAuthCookieOptions` — function: Base cookie attributes shared by EVERY auth cookie this resource sets and
512
- - `authorization.invalidateDeviceExistsCache` — function: Evict a single device's positive entry from the device-exists cache so the
513
- - `authorization.invalidateAllDeviceExistsCache` — function: Evict ALL positive entries from the device-exists cache.
514
- - `authorization.set` — function: Set authorization headers and cookie for a session.
515
- - `authorization.VerifyMiddlewareOptions` — interface: Options for {@link verifyMiddleware}.
516
- - `authorization.verifyMiddleware` — function: Middleware that verifies the JWT token from the `Authorization` header and sets `res.locals.session`.
514
+ ##### `authorization.getAuthCookieName(base)`
517
515
 
518
- #### `authorizers`
516
+ Resolve the actual cookie name for an auth cookie.
519
517
 
520
- Members:
518
+ In production the auth-bearing cookies get the `__Host-` prefix. Browsers
519
+ reject any `__Host-`-prefixed cookie that carries a `Domain` attribute (and
520
+ require `Secure` + `Path=/`), so a sibling subdomain (e.g. a tenant preview
521
+ at `<token>.preview.molecule.dev`) can no longer create a colliding
522
+ `.molecule.dev`-scoped duplicate that shadows the platform's real session
523
+ cookie — closing the cross-tenant cookie-tossing / session-fixation hole.
521
524
 
522
- - `authorizers.auth` — function: Middleware that checks if the request has an authenticated session (`res.locals.session.userId`).
523
- - `authorizers.authSelf` — function: Middleware that checks if the authenticated user's ID matches the `:id` route parameter.
524
- - `authorizers.RateLimitAuthOptions` — interface: Configuration for {@link rateLimit}.
525
- - `authorizers.rateLimit` — function: Creates an authorizer middleware that brute-force-protects an auth endpoint.
526
- - `authorizers.loginAccountKey` — function: Account-identifier extractor for the login endpoint: the submitted username
527
- - `authorizers.emailAccountKey` — function: Account-identifier extractor for the forgot-password endpoint: the submitted
528
- - `authorizers.paramIdAccountKey` — function: Account-identifier extractor for the verify-two-factor endpoint: the target
529
- - `authorizers.requireWebhookAuthenticity` — function: Middleware guarding the public `POST /users/payment-notification/:provider`
525
+ In dev/test the cookies are not `Secure` (plain HTTP origins), so a
526
+ `__Host-` cookie would be rejected by the browser; use the plain name there.
530
527
 
531
- #### `handlers`
528
+ Exported so consumers (e.g. molecule-dev's guest-session / OAuth-state code)
529
+ set and read the exact same name the platform expects.
530
+
531
+ ```typescript
532
+ function getAuthCookieName(base: string): string
533
+ ```
532
534
 
533
- Members:
534
-
535
- - `handlers.billingPortal` — function: Opens the bonded provider's hosted billing portal for the user, so they can
536
- - `handlers.handlePaymentNotification` — function: Generic payment notification handler that works with any bonded PaymentProvider. Reads the
537
- - `handlers.verifyPayment` — function: Generic payment verification handler that works with any bonded PaymentProvider. Reads the
538
- - `handlers.CreateRequest` — interface: Request body for user creation, including password and optional device name.
539
- - `handlers.create` — function: Creates a user with username and password. Validates username uniqueness and email format,
540
- - `handlers.del` — function: Deletes a user and their associated data. Deletes the user row FIRST, then
541
- - `handlers.ForgotPasswordRequest` — interface: Request body for password reset initiation.
542
- - `handlers.forgotPassword` — function: Generates a UUID password reset token, stores it in the secrets table, and sends a reset
543
- - `handlers.LogInRequest` — interface: Request body for user login, supporting password, reset token, and 2FA flows.
544
- - `handlers.logIn` — function: Logs in a user by username or email. Supports password authentication, password reset token
545
- - `handlers.LogInOAuthRequest` — interface: Request body for OAuth login, including the OAuth server name, authorization code, and PKCE verifier.
546
- - `handlers.logInOAuth` — function: Logs in or creates a user via OAuth. Verifies the authorization code with the bonded OAuth
547
- - `handlers.logout` — function: Logs the current user out. Revokes the session device server-side (so the JWT
548
- - `handlers.oauthAuthorize` — function: OAuth initiation — `GET /users/oauth/:provider`.
549
- - `handlers.read` — function: Reads a user by ID from the database. Attaches plan info (with expiration/renewal status) via the
550
- - `handlers.readSelf` — function: Reads the AUTHENTICATED user from the session — no `:id` param. Backs
551
- - `handlers.RESET_TOKEN_TTL_MS` — const: How long a password-reset token stays valid, in milliseconds. Shared with
552
- - `handlers.ResetPasswordRequest` — interface: Request body for confirming a password reset using a token.
553
- - `handlers.resetPassword` — function: Confirms a password reset by validating the one-time token previously generated by
554
- - `handlers.update` — function: Updates a user's profile fields (username, name, email). Validates username format
555
- - `handlers.UpdatePasswordRequest` — interface: Request body for password update, with current password verification and new password.
556
- - `handlers.updatePassword` — function: Updates a user's password. If the user already has a password hash, the current password
557
- - `handlers.UpdatePlanRequest` — interface: Request body for plan update, containing the target plan key.
558
- - `handlers.updatePlan` — function: Updates a user's subscription plan. Uses the bonded PlanService to look up plan metadata and
559
- - `handlers.VerifyTwoFactorRequest` — interface: Request body for two-factor authentication operations (setup, enable, or disable).
560
- - `handlers.verifyTwoFactor` — function: Handles two-factor authentication lifecycle via `@molecule/api-two-factor`:
535
+ - `base` — The base cookie name (e.g. `'token'`, `'sessionId'`).
561
536
 
562
- #### `types`
537
+ **Returns:** The environment-appropriate cookie name.
563
538
 
564
- Members:
565
-
566
- - `types.CreateOAuthProps` — type: Create O Auth Props type.
567
- - `types.CreateProps` — type: Create Props type.
568
- - `types.CreateSecretProps` — type: Create Secret Props type.
569
- - `types.Props` — type: User props type inferred from schema.
570
- - `types.SecretProps` — type: Secret Props type.
571
- - `types.Session` — type: User session data (userId, email, role, permissions, metadata) inferred from sessionSchema.
572
- - `types.UpdatePasswordSecretProps` — type: Update Password Secret Props type.
573
- - `types.UpdatePlanProps` — type: Update Plan Props type.
574
- - `types.UpdateProps` — type: Update Props type.
575
- - `types.VerifyTwoFactorProps` — type: Verify Two Factor Props type.
576
- - `types.VerifyTwoFactorSecretProps` — type: Verify Two Factor Secret Props type.
577
- - `types.Resource` — type: An object describing the `user` resource.
539
+ ##### `authorization.getAuthCookieOptions()`
578
540
 
579
- #### `utilities`
541
+ Base cookie attributes shared by EVERY auth cookie this resource sets and
542
+ clears — the single source of truth so a SET and its matching CLEAR always
543
+ agree (a mismatched attribute leaves an undeletable cookie) and every auth
544
+ cookie gets identical behaviour.
580
545
 
581
- Members:
546
+ - **Cross-site preview** (see {@link isCrossSitePreview}) → `{ secure: true,
547
+ sameSite: 'none', partitioned: true, path: '/' }`. The molecule.dev live
548
+ preview renders the app in a CROSS-SITE iframe; browsers evaluate SameSite
549
+ against the TOP-LEVEL site, so a `Lax`/`Strict` cookie is neither stored nor
550
+ sent on ANY preview request — the httpOnly session cookie vanishes on every
551
+ iframe reload and the user is logged out of their own app. `SameSite=None`
552
+ makes it cross-site-sendable (which REQUIRES `Secure` — permitted over http
553
+ on the potentially-trustworthy `localhost` / `127.0.0.1` origins), and
554
+ `Partitioned` (CHIPS) keeps it working when third-party cookies are blocked
555
+ (Brave/Chrome), which `None` alone does not. Applies whether the platform is
556
+ dev or prod, because the preview app is cross-site either way.
557
+ - **Production, top-level** → `{ secure: true, sameSite: 'lax', path: '/' }`.
558
+ The correct, CSRF-hardened default; pairs with the `__Host-` prefix (see
559
+ {@link getAuthCookieName}). NEVER weaken it.
560
+ - **Development, top-level** → `{ secure: false, sameSite: 'lax', path: '/' }`.
561
+ The original dev posture (plain http, not `Secure`) — used by the molecule.dev
582
562
 
583
- - `utilities.fetchAvatarDataUri` — function: Downloads an OAuth provider's profile image and re-hosts it as an inline
584
- - `utilities.getPlan` — function: Get a user's current plan info.
585
- - `utilities.invalidateEntitlementsCache` — function: Invalidates the entitlements plan-key cache for a user after their plan
586
- - `utilities.invalidateEntitlementsCacheSafe` — function: Fire-and-forget variant of {@link invalidateEntitlementsCache} for call
587
- - `utilities.normalizeEmail` — function: Normalizes an email address for storage and lookup so case/whitespace
588
- - `utilities.notify` — function: Sends push notifications to all of a user's devices except the current one. Retrieves devices
563
+ _(description truncated — read the full text in `node_modules/@molecule/api-resource-user/dist/authorization.d.ts`.)_
589
564
 
590
- #### `z`
565
+ ```typescript
566
+ function getAuthCookieOptions(): {
567
+ secure: boolean
568
+ sameSite: 'lax' | 'none'
569
+ partitioned?: boolean
570
+ path: string
571
+ }
572
+ ```
573
+
574
+ **Returns:** The environment-appropriate base cookie options.
575
+
576
+ ##### `authorization.invalidateDeviceExistsCache(deviceId)`
577
+
578
+ Evict a single device's positive entry from the device-exists cache so the
579
+ next authorization check for that device re-consults the database.
580
+
581
+ Call this from any in-process revocation path that deletes a specific device
582
+ row (e.g. a logout handler that knows the `deviceId`) so the revocation is
583
+ effective immediately on this instance rather than after the cache TTL.
584
+
585
+ ```typescript
586
+ function invalidateDeviceExistsCache(deviceId: string): void
587
+ ```
588
+
589
+ - `deviceId` — The device id whose cached "exists" result should be dropped.
590
+
591
+ ##### `authorization.invalidateAllDeviceExistsCache()`
592
+
593
+ Evict ALL positive entries from the device-exists cache.
594
+
595
+ Call this from in-process bulk revocation paths that delete every device for
596
+ a user (password change/reset, account deletion, OAuth account-claim) where
597
+ the affected device ids are not enumerated — the cache is keyed by deviceId,
598
+ not userId, so a full clear is the correct way to guarantee none of the
599
+ just-deleted devices keep authenticating on this instance. The normal-path
600
+ per-request DB-cost reduction is preserved: the cache simply repopulates on
601
+ subsequent requests; only these rare revocation events pay a brief re-check.
602
+
603
+ ```typescript
604
+ function invalidateAllDeviceExistsCache(): void
605
+ ```
606
+
607
+ ##### `authorization.set(_req, res, session)`
608
+
609
+ Set authorization headers and cookie for a session.
610
+
611
+ ```typescript
612
+ function set(
613
+ _req: MoleculeRequest,
614
+ res: MoleculeResponse,
615
+ session: {
616
+ userId: string
617
+ deviceId: string
618
+ id?: string | undefined
619
+ oauthServer?: string | undefined
620
+ oauthId?: string | undefined
621
+ },
622
+ ): string | null
623
+ ```
624
+
625
+ - `_req` — The request object (unused; reserved for handler signature parity).
626
+ - `res` — The response object.
627
+ - `session` — The session.
628
+
629
+ **Returns:** The signed JWT token string, or null if signing failed.
630
+
631
+ ##### `authorization.VerifyMiddlewareOptions`
632
+
633
+ Options for {@link verifyMiddleware}.
634
+
635
+ ```typescript
636
+ interface VerifyMiddlewareOptions {
637
+ /**
638
+ * Decide whether an aging token may be transparently re-issued for this
639
+ * session. The auto-refresh calls `set()`, which rewrites the session cookies
640
+ * AND the non-httpOnly `mol_auth` presence hint — the signal the auth client
641
+ * uses to hydrate a signed-in user on the next page load. Return `false` to
642
+ * skip the refresh for sessions that must never mint that hint (e.g. an
643
+ * anonymous/guest session whose httpOnly cookie authenticates API calls but
644
+ * whose user must not appear signed-in client-side). A thrown error is
645
+ * treated as `false` (refresh is best-effort and fails safe: no hint).
646
+ * Defaults to refreshing every session.
647
+ * @param session - The verified session about to be refreshed.
648
+ * @param req - The current request.
649
+ * @returns Whether the session may be re-issued.
650
+ */
651
+ shouldRefreshSession?: (session: Session, req: MoleculeRequest) => boolean | Promise<boolean>
652
+ /**
653
+ * Accept the `token` cookie as the session when no `Authorization` header is sent.
654
+ * Defaults to `true` (browser clients sign in once and every page request carries
655
+ * the cookie). Pass `false` for a token-only JSON API: any client that keeps a
656
+ * cookie jar (an HTTP test runner, `curl -b`) would otherwise arrive authenticated
657
+ * on a request that sends no header, and get 200 where the API should answer 401.
658
+ */
659
+ allowCookieSession?: boolean
660
+ }
661
+ ```
662
+
663
+ ##### `authorization.verifyMiddleware(options)`
664
+
665
+ Middleware that verifies the JWT token from the `Authorization` header and sets `res.locals.session`.
666
+ Falls back to cookie-based session for browser clients unless `allowCookieSession` is `false`. Auto-refreshes tokens older than `JWT_REFRESH_TIME`.
667
+
668
+ ```typescript
669
+ function verifyMiddleware(options?: VerifyMiddlewareOptions): MoleculeRequestHandler
670
+ ```
671
+
672
+ - `options` — {@link VerifyMiddlewareOptions} controlling the auto-refresh.
673
+
674
+ **Returns:** An Express-compatible middleware function.
675
+
676
+ #### `authorizers`
677
+
678
+ Re-exported as a namespace — reach every member below through it (e.g. `authorizers.<name>`).
679
+
680
+ ##### `authorizers.auth()`
681
+
682
+ Middleware that checks if the request has an authenticated session (`res.locals.session.userId`).
683
+ Calls `next()` on success or `next('Unauthorized')` on failure.
684
+
685
+ ```typescript
686
+ function auth(): MoleculeRequestHandler
687
+ ```
688
+
689
+ **Returns:** An Express-compatible middleware function.
690
+
691
+ ##### `authorizers.authSelf()`
692
+
693
+ Middleware that checks if the authenticated user's ID matches the `:id` route parameter.
694
+ Ensures users can only access their own resource. Calls `next()` on match or `next('Unauthorized')` otherwise.
695
+
696
+ As a convenience, `:id === 'me'` is treated as the current authenticated
697
+ user — `req.params.id` is rewritten to the session's userId so downstream
698
+ handlers receive the real id. This lets pages call `/api/users/me`
699
+ without needing the user's UUID in scope.
700
+
701
+ ```typescript
702
+ function authSelf(): MoleculeRequestHandler
703
+ ```
704
+
705
+ **Returns:** An Express-compatible middleware function.
706
+
707
+ ##### `authorizers.RateLimitAuthOptions`
708
+
709
+ Configuration for {@link rateLimit}.
710
+
711
+ ```typescript
712
+ interface RateLimitAuthOptions {
713
+ /**
714
+ * Key namespace so each protected surface gets an isolated bucket
715
+ * (e.g. `'login'`, `'forgot-password'`, `'2fa'`). Buckets never collide
716
+ * across scopes.
717
+ */
718
+ scope: string
719
+
720
+ /** Sliding window in milliseconds (default: 15 minutes). */
721
+ windowMs?: number
722
+
723
+ /**
724
+ * Maximum attempts per window for the per-account bucket before a 429
725
+ * (default: 10). This is the tight brute-force gate; a legitimate user makes
726
+ * only a handful of attempts, so it never trips for them.
727
+ */
728
+ max?: number
729
+
730
+ /**
731
+ * Maximum attempts per window for the per-IP bucket (default: 60). Kept
732
+ * higher than {@link RateLimitAuthOptions.max} so shared public IPs aren't
733
+ * locked out; primarily catches single-source flooding and password-spray
734
+ * across many accounts, and is the only guard when no account is resolvable
735
+ * (e.g. an OAuth login carrying no email).
736
+ */
737
+ ipMax?: number
738
+
739
+ /**
740
+ * Optional extractors for an account identifier (submitted email/username,
741
+ * the target user id, etc.). When one resolves, the request is ALSO bucketed
742
+ * per account — so a distributed attack against a single account is throttled
743
+ * even when the source IP rotates, and the second factor is temp-locked after
744
+ * `max` consecutive misses regardless of IP. Each extractor is tried; every
745
+ * value that resolves contributes a bucket.
746
+ */
747
+ accountFrom?: ReadonlyArray<(req: MoleculeRequest) => string | undefined>
748
+ }
749
+ ```
750
+
751
+ ##### `authorizers.rateLimit(options)`
752
+
753
+ Creates an authorizer middleware that brute-force-protects an auth endpoint.
754
+
755
+ Consumes a rate-limit token per request, keyed by client IP and — where
756
+ resolvable — by account identifier, returning HTTP 429 once the low ceiling
757
+ is exceeded. This closes the unthrottled-auth default that left passwords and
758
+ the 6-digit TOTP second factor brute-forceable on `mlcl`-generated apps.
759
+
760
+ Availability is preserved over absolute enforcement: if no rate-limit
761
+ provider is bonded (an app deliberately removed it) or the limiter itself
762
+ errors, the request is allowed through (with a logged warning/error) so a
763
+ limiter outage never locks out every legitimate login. Generated apps wire
764
+ the default in-memory provider via the registry's `alwaysInclude`/
765
+ `defaultProvider`, so the throttle is active out of the box.
766
+
767
+ ```typescript
768
+ function rateLimit(options: RateLimitAuthOptions): MoleculeRequestHandler
769
+ ```
770
+
771
+ - `options` — Scope, window, ceiling, and optional account-key extractors.
772
+
773
+ **Returns:** A `MoleculeRequestHandler` to place ahead of the protected handler.
774
+
775
+ ##### `authorizers.loginAccountKey(req)`
776
+
777
+ Account-identifier extractor for the login endpoint: the submitted username
778
+ or email. Bucketing on this temp-locks a single targeted account after `max`
779
+ failed attempts even across rotating IPs (which also covers TOTP-via-login
780
+ brute force, since the login handler verifies the second factor).
781
+
782
+ ```typescript
783
+ function loginAccountKey(req: MoleculeRequest): string | undefined
784
+ ```
785
+
786
+ - `req` — The incoming request.
787
+
788
+ **Returns:** The submitted username or email (if present).
789
+
790
+ ##### `authorizers.emailAccountKey(req)`
791
+
792
+ Account-identifier extractor for the forgot-password endpoint: the submitted
793
+ email.
794
+
795
+ ```typescript
796
+ function emailAccountKey(req: MoleculeRequest): string | undefined
797
+ ```
798
+
799
+ - `req` — The incoming request.
800
+
801
+ **Returns:** The submitted email (if present).
802
+
803
+ ##### `authorizers.paramIdAccountKey(req)`
804
+
805
+ Account-identifier extractor for the verify-two-factor endpoint: the target
806
+ user id in the route params. Temp-locks the second factor per account after
807
+ `max` consecutive misses.
808
+
809
+ ```typescript
810
+ function paramIdAccountKey(req: MoleculeRequest): string | undefined
811
+ ```
812
+
813
+ - `req` — The incoming request.
814
+
815
+ **Returns:** The target user id (if present).
816
+
817
+ ##### `authorizers.requireWebhookAuthenticity()`
818
+
819
+ Middleware guarding the public `POST /users/payment-notification/:provider`
820
+ endpoint against forged server-to-server (Apple/Google IAP) notifications.
821
+
822
+ Self-verifying webhook providers (e.g. Stripe) authenticate the payload by
823
+ cryptographic signature INSIDE the handler (`constructEvent`), so they pass
824
+ through untouched.
825
+
826
+ Server-to-server providers (Apple/Google RTDN) carry no transport signature —
827
+ their endpoint is otherwise open to anyone — so a shared secret is REQUIRED by
828
+ default ("IAP apps are not open by default"). The secret is supplied via the
829
+ `x-payment-notification-secret` header or `?secret=` query param (configure
830
+ the provider's notification URL accordingly) and is compared in constant time
831
+ against `PAYMENT_NOTIFICATION_SECRET`. Deployments that rely solely on the
832
+ provider's in-handler receipt re-verification can opt out with
833
+ `PAYMENT_NOTIFICATION_REQUIRE_SECRET=false` — but the secure behavior ships ON
834
+ by default and is never relaxed based on request presence.
835
+
836
+ ```typescript
837
+ function requireWebhookAuthenticity(): MoleculeRequestHandler
838
+ ```
839
+
840
+ **Returns:** An Express-compatible middleware function.
841
+
842
+ #### `handlers`
843
+
844
+ Re-exported as a namespace — reach every member below through it (e.g. `handlers.<name>`).
845
+
846
+ ##### `handlers.CreateRequest`
847
+
848
+ Request body for user creation, including password and optional device name.
849
+
850
+ ```typescript
851
+ interface CreateRequest extends MoleculeRequest {
852
+ body: types.CreateProps & {
853
+ password?: string
854
+ deviceName?: string
855
+ }
856
+ }
857
+ ```
858
+
859
+ ##### `handlers.create(resource)`
860
+
861
+ Creates a user with username and password. Validates username uniqueness and email format,
862
+ hashes the password into a separate secrets table, creates a session device via the bonded
863
+ DeviceService, and sets JWT authorization on the response.
864
+
865
+ ```typescript
866
+ function create({ name, tableName, schema }: types.Resource<unknown>): (
867
+ req: CreateRequest,
868
+ res: MoleculeResponse,
869
+ ) => Promise<
870
+ | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
871
+ | {
872
+ statusCode: number
873
+ body: { props: Props & Record<string, unknown>; error?: undefined; errorKey?: undefined }
874
+ }
875
+ | {
876
+ statusCode: number
877
+ body: {
878
+ props: Record<string, unknown>
879
+ accessToken: string | null
880
+ user: Record<string, unknown>
881
+ }
882
+ }
883
+ >
884
+ ```
885
+
886
+ - `resource` — The user resource configuration (name, tableName, schema).
887
+ - `resource.name` — The resource name.
888
+ - `resource.tableName` — The database table name for users.
889
+ - `resource.schema` — The validation schema for user properties.
890
+
891
+ **Returns:** A request handler that responds with `{ statusCode: 201, body: { props } }` on success.
892
+
893
+ ##### `handlers.del(resource)`
894
+
895
+ Deletes a user and their associated data. Deletes the user row FIRST, then
896
+ the secrets, the devices (via the bonded DeviceService) and the payment
897
+ records (via the bonded PaymentRecordService).
898
+
899
+ The row goes first so that a failed delete changes nothing: deleting the
900
+ secrets first meant a row delete that then failed left an account with no
901
+ password hash — no password sign-in, and a retried delete that no longer
902
+ asks for one. When the row delete fails nothing else has been touched; when
903
+ it succeeds, a failure in the clean-up after it leaves records that belong
904
+ to no account (logged), never an account without its password.
905
+
906
+ ```typescript
907
+ function del({
908
+ name: _name,
909
+ tableName,
910
+ schema: _schema,
911
+ }: types.Resource<unknown>): (
912
+ req: MoleculeRequest,
913
+ ) => Promise<
914
+ | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
915
+ | { statusCode: number; body: { props: { id: string }; error?: undefined; errorKey?: undefined } }
916
+ >
917
+ ```
918
+
919
+ - `resource` — The user resource configuration (name, tableName, schema).
920
+ - `resource.name` — The resource name.
921
+ - `resource.tableName` — The database table name for users.
922
+ - `resource.schema` — The validation schema for user properties.
923
+
924
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { props: { id } } }` on success.
925
+
926
+ ##### `handlers.ForgotPasswordRequest`
927
+
928
+ Request body for password reset initiation.
929
+
930
+ ```typescript
931
+ interface ForgotPasswordRequest extends MoleculeRequest {
932
+ body: {
933
+ email?: string
934
+ }
935
+ }
936
+ ```
937
+
938
+ ##### `handlers.forgotPassword(resource)`
939
+
940
+ Generates a UUID password reset token, stores it in the secrets table, and sends a reset
941
+ email via the bonded email provider (if available). Always returns 200 regardless of whether
942
+ the email exists, to prevent user enumeration.
943
+
944
+ ```typescript
945
+ function forgotPassword({
946
+ name: _name,
947
+ tableName,
948
+ schema: _schema,
949
+ }: types.Resource<unknown>): (
950
+ req: ForgotPasswordRequest,
951
+ ) => Promise<
952
+ | { statusCode: number; body: { error: string; errorKey: string; success?: undefined } }
953
+ | { statusCode: number; body: { success: boolean; error?: undefined; errorKey?: undefined } }
954
+ >
955
+ ```
956
+
957
+ - `resource` — The user resource configuration (name, tableName, schema).
958
+ - `resource.name` — The resource name.
959
+ - `resource.tableName` — The database table name for users.
960
+ - `resource.schema` — The validation schema for user properties.
961
+
962
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { success: true } }`.
963
+
964
+ ##### `handlers.LogInRequest`
965
+
966
+ Request body for user login, supporting password, reset token, and 2FA flows.
967
+
968
+ ```typescript
969
+ interface LogInRequest extends MoleculeRequest {
970
+ body: {
971
+ username?: string
972
+ email?: string
973
+ password?: string
974
+ passwordResetToken?: string
975
+ twoFactorToken?: string
976
+ deviceName?: string
977
+ }
978
+ }
979
+ ```
980
+
981
+ ##### `handlers.logIn(resource)`
982
+
983
+ Logs in a user by username or email. Supports password authentication, password reset token
984
+ authentication (1-hour expiry), and optional two-factor verification via `@molecule/api-two-factor`.
985
+ On success, creates/updates a device via the bonded DeviceService, sets JWT authorization,
986
+ and notifies other devices about the new login.
987
+
988
+ ```typescript
989
+ function logIn({ name: _name, tableName, schema: _schema }: types.Resource<unknown>): (
990
+ req: LogInRequest,
991
+ res: MoleculeResponse,
992
+ ) => Promise<
993
+ | {
994
+ statusCode: number
995
+ body: {
996
+ error: string
997
+ errorKey: string
998
+ twoFactorRequired?: undefined
999
+ props?: undefined
1000
+ accessToken?: undefined
1001
+ user?: undefined
1002
+ }
1003
+ }
1004
+ | {
1005
+ statusCode: number
1006
+ body: {
1007
+ twoFactorRequired: boolean
1008
+ error?: undefined
1009
+ errorKey?: undefined
1010
+ props?: undefined
1011
+ accessToken?: undefined
1012
+ user?: undefined
1013
+ }
1014
+ }
1015
+ | {
1016
+ statusCode: number
1017
+ body: {
1018
+ props: Record<string, unknown>
1019
+ accessToken: string | null
1020
+ user: Record<string, unknown>
1021
+ error?: undefined
1022
+ errorKey?: undefined
1023
+ twoFactorRequired?: undefined
1024
+ }
1025
+ }
1026
+ >
1027
+ ```
1028
+
1029
+ - `resource` — The user resource configuration (name, tableName, schema).
1030
+ - `resource.name` — The resource name.
1031
+ - `resource.tableName` — The database table name for users.
1032
+ - `resource.schema` — The validation schema for user properties.
1033
+
1034
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { props } }` on success, or `{ statusCode: 206, body: { twoFactorRequired: true } }` when 2FA is needed.
1035
+
1036
+ ##### `handlers.LogInOAuthRequest`
1037
+
1038
+ Request body for OAuth login, including the OAuth server name, authorization code, and PKCE verifier.
1039
+
1040
+ ```typescript
1041
+ interface LogInOAuthRequest extends MoleculeRequest {
1042
+ body: {
1043
+ server?: string
1044
+ code?: string
1045
+ state?: string
1046
+ codeVerifier?: string
1047
+ redirect_uri?: string
1048
+ deviceName?: string
1049
+ }
1050
+ }
1051
+ ```
1052
+
1053
+ ##### `handlers.logInOAuth(resource)`
1054
+
1055
+ Logs in or creates a user via OAuth. Verifies the authorization code with the bonded OAuth
1056
+ provider (`get('oauth', serverName)`), then either finds an existing user by oauthServer+oauthId
1057
+ or creates a new one with a unique username. Sets JWT authorization and creates a session device.
1058
+
1059
+ ```typescript
1060
+ function logInOAuth({ name, tableName, schema }: types.Resource<unknown>): (
1061
+ req: LogInOAuthRequest,
1062
+ res: MoleculeResponse,
1063
+ ) => Promise<
1064
+ | {
1065
+ statusCode: number
1066
+ body: { error: string; errorKey: string; twoFactorRequired?: undefined; props?: undefined }
1067
+ }
1068
+ | {
1069
+ statusCode: number
1070
+ body: { error: string; errorKey: string; twoFactorRequired: boolean; props?: undefined }
1071
+ }
1072
+ | {
1073
+ statusCode: number
1074
+ body: {
1075
+ props: Record<string, unknown>
1076
+ error?: undefined
1077
+ errorKey?: undefined
1078
+ twoFactorRequired?: undefined
1079
+ }
1080
+ }
1081
+ >
1082
+ ```
1083
+
1084
+ - `resource` — The user resource configuration (name, tableName, schema).
1085
+ - `resource.name` — The resource name.
1086
+ - `resource.tableName` — The database table name for users.
1087
+ - `resource.schema` — The validation schema for user properties.
1088
+
1089
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { props } }` on success.
1090
+
1091
+ ##### `handlers.logout()`
1092
+
1093
+ Logs the current user out. Revokes the session device server-side (so the JWT
1094
+ is rejected on its next use — covering EVERY copy of the token, not just this
1095
+ browser) and clears the credential cookies.
1096
+
1097
+ [M1-1] Under the in-memory-token model the httpOnly `token` cookie is the
1098
+ persistent credential, so logout MUST clear it (and the `mol_auth` presence
1099
+ hint) — otherwise the app's cookie-based session restore (`GET /users/me` on
1100
+ init) would silently log the user back in on the next page load, and a
1101
+ client-side-only logout would be cosmetic (the cookie would still authenticate
1102
+ direct API calls). Cookie-authed via `auth` (no `:id`; the session identifies
1103
+ the user).
1104
+
1105
+ ```typescript
1106
+ function logout(): (
1107
+ _req: MoleculeRequest,
1108
+ res: MoleculeResponse,
1109
+ ) => Promise<{ statusCode: number; body: { success: boolean } }>
1110
+ ```
1111
+
1112
+ **Returns:** A request handler responding `{ statusCode: 200, body: { success: true } }`.
1113
+
1114
+ ##### `handlers.oauthAuthorize()`
1115
+
1116
+ OAuth initiation — `GET /users/oauth/:provider`.
1117
+
1118
+ The missing first half of the OAuth flow whose second half is
1119
+ `logInOAuth` (`POST /users/log-in/oauth`): generates the CSRF `state` and
1120
+ a per-session PKCE S256 verifier, stores BOTH in httpOnly cookies (the
1121
+ exact names + attributes `logInOAuth` reads and clears —
1122
+ `getAuthCookieName('oauth_state')` / `('oauth_verifier')` with
1123
+ `getAuthCookieOptions()`), then 302-redirects the browser to the
1124
+ provider's authorization URL.
1125
+
1126
+ Provider knowledge stays in the bond: the handler asks the bonded OAuth
1127
+ provider (`get('oauth', :provider)`) for its authorize URL via its
1128
+ optional `getAuthorizeUrl` builder (see `@molecule/api-oauth`). A
1129
+ provider that is not bonded, lacks the builder, or is unconfigured
1130
+ (builder returns `null`, e.g. missing client id) yields a clean 404/503 —
1131
+ never a crash.
1132
+
1133
+ The `redirect_uri` sent to the provider is `APP_ORIGIN` plus an optional
1134
+ validated same-origin `redirect_to` path from the query string (the page
1135
+ that initiated the flow, e.g. `/login`, where the app's OAuth callback
1136
+ handling is mounted). The path is sanitized so this can never become an
1137
+ open redirect; the state cookie — not `redirect_uri` — is the CSRF
1138
+ control.
1139
+
1140
+ ```typescript
1141
+ function oauthAuthorize(): (
1142
+ req: MoleculeRequest,
1143
+ res: MoleculeResponse,
1144
+ ) => Promise<
1145
+ | { statusCode: number; body: { error: string; errorKey: string }; headers?: undefined }
1146
+ | { statusCode: number; headers: { Location: string }; body: undefined }
1147
+ >
1148
+ ```
1149
+
1150
+ **Returns:** A request handler that responds `302` with a `Location` header pointing at the provider's authorization URL.
1151
+
1152
+ ##### `handlers.billingPortal()`
1153
+
1154
+ Opens the bonded provider's hosted billing portal for the user, so they can
1155
+ update their payment method, see invoices, and cancel — the self-service
1156
+ surface an app otherwise has to build (and usually doesn't, leaving a
1157
+ subscriber with no way out but support).
1158
+
1159
+ Reads the provider name from the `:provider` route parameter and returns the
1160
+ portal URL for the client to open. Providers whose purchases are managed by
1161
+ the platform store (Apple/Google) implement no portal and answer 400 —
1162
+ their subscribers manage the subscription in the store app.
1163
+
1164
+ The user is returned to the APP origin on exit (never the API origin, whose
1165
+ host holds no session cookie); an app-relative `returnPath` in the request
1166
+ body sends them back to the exact page they opened the portal from.
1167
+
1168
+ ```typescript
1169
+ function billingPortal(): (req: MoleculeRequest) => Promise<
1170
+ | {
1171
+ statusCode: number
1172
+ body: { error: string; errorKey: string; id?: undefined; url?: undefined }
1173
+ }
1174
+ | {
1175
+ statusCode: number
1176
+ body: { id: string; url: string; error?: undefined; errorKey?: undefined }
1177
+ }
1178
+ >
1179
+ ```
1180
+
1181
+ **Returns:** A request handler that responds `{ url, id }` with the portal session.
1182
+
1183
+ ##### `handlers.handlePaymentNotification(resource)`
1184
+
1185
+ Generic payment notification handler that works with any bonded PaymentProvider. Reads the
1186
+ provider name from the `:provider` route parameter and dispatches based on `notificationFlow`:
1187
+
1188
+ - `'webhook'` (Stripe-style): Calls `handleWebhookEvent()` to parse signed webhook payloads,
1189
+ then looks up the user via PaymentRecordService by customer ID.
1190
+ - Default (Apple/Google-style): Calls `parseNotification()` for server-to-server notifications,
1191
+ then looks up the user via PaymentRecordService by transaction ID.
1192
+
1193
+ Updates the user's plan on renewal/change or clears it on cancellation/expiry/refund/revocation.
1194
+ Always returns 200 to acknowledge receipt.
1195
+
1196
+ ```typescript
1197
+ function handlePaymentNotification({
1198
+ name,
1199
+ tableName,
1200
+ schema: _schema,
1201
+ }: types.Resource<unknown>): (
1202
+ req: MoleculeRequest,
1203
+ ) => Promise<{ statusCode: number; body: string } | { statusCode: number; body: { error: string } }>
1204
+ ```
1205
+
1206
+ - `resource` — The user resource configuration (name, tableName, schema).
1207
+ - `resource.name` — The resource name.
1208
+ - `resource.tableName` — The database table name for users.
1209
+ - `resource.schema` — The validation schema for user properties.
1210
+
1211
+ **Returns:** A request handler for payment provider notifications.
1212
+
1213
+ ##### `handlers.verifyPayment(resource)`
1214
+
1215
+ Generic payment verification handler that works with any bonded PaymentProvider. Reads the
1216
+ provider name from the `:provider` route parameter and dispatches based on `verifyFlow`:
1217
+
1218
+ - `'subscription'` (Stripe-style): Calls `verifySubscription(subscriptionId)`.
1219
+ - Default (Apple/Google-style): Calls `verifyReceipt()` or `verifyPurchase()` with a receipt
1220
+ string and the plan's platform product ID.
1221
+
1222
+ On successful verification, updates the user's plan (planKey, planExpiresAt, planAutoRenews)
1223
+ and stores the payment record via the bonded PaymentRecordService.
1224
+
1225
+ ```typescript
1226
+ function verifyPayment({ name, tableName, schema: _schema }: types.Resource<unknown>): (
1227
+ req: MoleculeRequest,
1228
+ ) => Promise<
1229
+ | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
1230
+ | {
1231
+ statusCode: number
1232
+ body: {
1233
+ props: Pick<Props, 'updatedAt'> & {
1234
+ planKey?: string | undefined
1235
+ planExpiresAt?: string | undefined
1236
+ planAutoRenews?: boolean | undefined
1237
+ }
1238
+ error?: undefined
1239
+ errorKey?: undefined
1240
+ }
1241
+ }
1242
+ >
1243
+ ```
1244
+
1245
+ - `resource` — The user resource configuration (name, tableName, schema).
1246
+ - `resource.name` — The resource name.
1247
+ - `resource.tableName` — The database table name for users.
1248
+ - `resource.schema` — The validation schema for user properties.
1249
+
1250
+ **Returns:** A request handler for payment verification.
1251
+
1252
+ ##### `handlers.read(resource)`
1253
+
1254
+ Reads a user by ID from the database. Attaches plan info (with expiration/renewal status) via the
1255
+ bonded PlanService if available. When reading the authenticated user's own record, also includes
1256
+ two-factor authentication status from the secrets table.
1257
+
1258
+ ```typescript
1259
+ function read({
1260
+ name: _name,
1261
+ tableName,
1262
+ schema: _schema,
1263
+ }: types.Resource<unknown>): (
1264
+ req: MoleculeRequest,
1265
+ res: MoleculeResponse,
1266
+ ) => Promise<{ statusCode: number; body: Record<string, unknown> }>
1267
+ ```
1268
+
1269
+ - `resource` — The user resource configuration (name, tableName, schema).
1270
+ - `resource.name` — The resource name.
1271
+ - `resource.tableName` — The database table name for users.
1272
+ - `resource.schema` — The validation schema for user properties.
1273
+
1274
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { props, plan?, twoFactorEnabled? } }`.
1275
+
1276
+ ##### `handlers.readSelf(resource)`
1277
+
1278
+ Reads the AUTHENTICATED user from the session — no `:id` param. Backs
1279
+ `GET /users/me`, which the app's auth client calls on init to RESTORE the
1280
+ session after a full page load.
1281
+
1282
+ [M1-1] The bearer token is held in memory (a localStorage copy is
1283
+ XSS-exfiltratable and is forbidden), so it is lost on reload; the httpOnly
1284
+ session cookie is the persistent credential. The `auth` middleware reads that
1285
+ cookie into `res.locals.session`, and this handler returns the current user
1286
+ so the client can re-establish `authenticated` state WITHOUT the token ever
1287
+ being exposed to JavaScript. Always self, so it mirrors `read`'s self branch
1288
+ (plan + two-factor status).
1289
+
1290
+ ```typescript
1291
+ function readSelf({
1292
+ tableName,
1293
+ }: types.Resource<unknown>): (
1294
+ _req: MoleculeRequest,
1295
+ res: MoleculeResponse,
1296
+ ) => Promise<{ statusCode: number; body: Record<string, unknown> }>
1297
+ ```
1298
+
1299
+ - `resource` — The user resource configuration (name, tableName, schema).
1300
+ - `resource.tableName` — The database table name for users.
1301
+
1302
+ **Returns:** A request handler responding `{ statusCode: 200, body: { props, plan?, twoFactorEnabled? } }`, or 401 when unauthenticated.
1303
+
1304
+ ##### `handlers.RESET_TOKEN_TTL_MS`
1305
+
1306
+ How long a password-reset token stays valid, in milliseconds. Shared with
1307
+ `logIn`, which accepts the same token as a login credential and must apply
1308
+ the SAME gate — the same constant AND the same boundary (`tokenAge` equal to
1309
+ the TTL is still valid in both), or one path becomes the looser way in for
1310
+ the other's one-hour credential.
1311
+
1312
+ ```typescript
1313
+ const RESET_TOKEN_TTL_MS: number
1314
+ ```
1315
+
1316
+ ##### `handlers.ResetPasswordRequest`
1317
+
1318
+ Request body for confirming a password reset using a token.
1319
+
1320
+ ```typescript
1321
+ interface ResetPasswordRequest extends MoleculeRequest {
1322
+ body: {
1323
+ token?: string
1324
+ password?: string
1325
+ }
1326
+ }
1327
+ ```
1328
+
1329
+ ##### `handlers.resetPassword(resource)`
1330
+
1331
+ Confirms a password reset by validating the one-time token previously generated by
1332
+ `forgotPassword`, then hashing and storing the new password and clearing the token.
1333
+
1334
+ Token TTL is one hour. The handler responds with 400 for missing fields, 400 for
1335
+ passwords that fail length validation (matching `updatePassword`), and 401 for
1336
+ tokens that are unknown, expired, or already consumed.
1337
+
1338
+ On success, all existing device sessions are invalidated to force a fresh login,
1339
+ mirroring the behavior of `updatePassword`.
1340
+
1341
+ The new password and the token clear are written as ONE WHERE-guarded update
1342
+ matching the verified token hash, so the link is consumed atomically: of two
1343
+ concurrent requests holding the same link, only the one that flips the token
1344
+ to NULL matches a row — the other is refused with 401 and cannot overwrite
1345
+ the winner's password.
1346
+
1347
+ ```typescript
1348
+ function resetPassword({
1349
+ name: _name,
1350
+ tableName,
1351
+ schema: _schema,
1352
+ }: types.Resource<unknown>): (
1353
+ req: ResetPasswordRequest,
1354
+ ) => Promise<
1355
+ | { statusCode: number; body: { error: string; errorKey: string; success?: undefined } }
1356
+ | { statusCode: number; body: { success: boolean; error?: undefined; errorKey?: undefined } }
1357
+ >
1358
+ ```
1359
+
1360
+ - `resource` — The user resource configuration (name, tableName, schema).
1361
+ - `resource.tableName` — The database table name for users.
1362
+
1363
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { success: true } }` on success.
1364
+
1365
+ ##### `handlers.update(resource)`
1366
+
1367
+ Updates a user's profile fields (username, name, email). Validates username format
1368
+ (alphanumeric, max 255 chars), email format, and uniqueness of both fields against
1369
+ other users before delegating to the resource update utility.
1370
+
1371
+ ```typescript
1372
+ function update({ name, tableName, schema: _schema }: types.Resource<unknown>): (
1373
+ req: MoleculeRequest,
1374
+ ) => Promise<
1375
+ | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
1376
+ | {
1377
+ statusCode: number
1378
+ body: {
1379
+ props: Pick<Props, 'updatedAt'> & Record<string, unknown>
1380
+ error?: undefined
1381
+ errorKey?: undefined
1382
+ }
1383
+ }
1384
+ >
1385
+ ```
1386
+
1387
+ - `resource` — The user resource configuration (name, tableName, schema).
1388
+ - `resource.name` — The resource name.
1389
+ - `resource.tableName` — The database table name for users.
1390
+ - `resource.schema` — The validation schema for user properties.
1391
+
1392
+ **Returns:** A request handler that responds with the updated user props on success.
1393
+
1394
+ ##### `handlers.UpdatePasswordRequest`
1395
+
1396
+ Request body for password update, with current password verification and new password.
1397
+
1398
+ ```typescript
1399
+ interface UpdatePasswordRequest extends MoleculeRequest {
1400
+ body: {
1401
+ currentPassword?: string
1402
+ newPassword?: string
1403
+ }
1404
+ }
1405
+ ```
1406
+
1407
+ ##### `handlers.updatePassword(resource)`
1408
+
1409
+ Updates a user's password. If the user already has a password hash, the current password
1410
+ must be provided and verified first. The new password is hashed via `@molecule/api-password`
1411
+ and stored in the secrets table.
1412
+
1413
+ ```typescript
1414
+ function updatePassword({
1415
+ name: _name,
1416
+ tableName,
1417
+ schema: _schema,
1418
+ }: types.Resource<unknown>): (
1419
+ req: UpdatePasswordRequest,
1420
+ ) => Promise<
1421
+ | { statusCode: number; body: { error: string; errorKey: string; success?: undefined } }
1422
+ | { statusCode: number; body: { success: boolean; error?: undefined; errorKey?: undefined } }
1423
+ >
1424
+ ```
1425
+
1426
+ - `resource` — The user resource configuration (name, tableName, schema).
1427
+ - `resource.name` — The resource name.
1428
+ - `resource.tableName` — The database table name for users.
1429
+ - `resource.schema` — The validation schema for user properties.
1430
+
1431
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { success: true } }` on success.
1432
+
1433
+ ##### `handlers.UpdatePlanRequest`
1434
+
1435
+ Request body for plan update, containing the target plan key.
1436
+
1437
+ ```typescript
1438
+ interface UpdatePlanRequest extends MoleculeRequest {
1439
+ body: {
1440
+ planKey?: string
1441
+ /**
1442
+ * Units of the plan to buy — seats, on a per-seat plan. Omitted means one.
1443
+ *
1444
+ * Read from the request because only the app knows what a unit means: the
1445
+ * plan catalogue describes a price, not how many of it this buyer wants.
1446
+ * Ignored by flat-priced plans, whose providers receive no quantity at all.
1447
+ */
1448
+ quantity?: number
1449
+ }
1450
+ }
1451
+ ```
1452
+
1453
+ ##### `handlers.updatePlan(resource)`
1454
+
1455
+ Updates a user's subscription plan. Uses the bonded PlanService to look up plan metadata and
1456
+ delegates to the appropriate bonded PaymentProvider based on the plan's `platformKey`. Handles
1457
+ cross-platform subscription cancellation when switching providers. Returns a checkout URL
1458
+ (status 201) for new subscriptions, or directly updates the user record for in-place changes
1459
+ and free plan downgrades.
1460
+
1461
+ ```typescript
1462
+ function updatePlan({ name, tableName, schema: _schema }: types.Resource<unknown>): (
1463
+ req: UpdatePlanRequest,
1464
+ ) => Promise<
1465
+ | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
1466
+ | {
1467
+ statusCode: number
1468
+ body: {
1469
+ props: Pick<Props, 'updatedAt'> & Record<string, unknown>
1470
+ error?: undefined
1471
+ errorKey?: undefined
1472
+ }
1473
+ }
1474
+ | { statusCode: number; body: { checkoutUrl: string } }
1475
+ >
1476
+ ```
1477
+
1478
+ - `resource` — The user resource configuration (name, tableName, schema).
1479
+ - `resource.name` — The resource name.
1480
+ - `resource.tableName` — The database table name for users.
1481
+ - `resource.schema` — The validation schema for user properties.
1482
+
1483
+ **Returns:** A request handler for plan updates.
1484
+
1485
+ ##### `handlers.VerifyTwoFactorRequest`
1486
+
1487
+ Request body for two-factor authentication operations (setup, enable, or disable).
1488
+
1489
+ ```typescript
1490
+ interface VerifyTwoFactorRequest extends MoleculeRequest {
1491
+ body: {
1492
+ token?: string
1493
+ action?: 'setup' | 'enable' | 'disable'
1494
+ }
1495
+ }
1496
+ ```
1497
+
1498
+ ##### `handlers.verifyTwoFactor(resource)`
1499
+
1500
+ Handles two-factor authentication lifecycle via `@molecule/api-two-factor`:
1501
+
1502
+ - `setup`: Generates a TOTP secret and returns QR code URLs for authenticator apps.
1503
+ - `enable`: Verifies a TOTP token against the pending secret, then activates 2FA.
1504
+ - `disable`: Verifies a TOTP token against the active secret, then deactivates 2FA.
1505
+
1506
+ ```typescript
1507
+ function verifyTwoFactor({ name: _name, tableName, schema: _schema }: types.Resource<unknown>): (
1508
+ req: VerifyTwoFactorRequest,
1509
+ ) => Promise<
1510
+ | { statusCode: number; body: { error: string; errorKey: string; twoFactorEnabled?: undefined } }
1511
+ | {
1512
+ statusCode: number
1513
+ body: {
1514
+ secret: string
1515
+ keyUrl: string
1516
+ QRImageUrl: string
1517
+ error?: undefined
1518
+ errorKey?: undefined
1519
+ twoFactorEnabled?: undefined
1520
+ }
1521
+ }
1522
+ | {
1523
+ statusCode: number
1524
+ body: { twoFactorEnabled: boolean; error?: undefined; errorKey?: undefined }
1525
+ }
1526
+ >
1527
+ ```
1528
+
1529
+ - `resource` — The user resource configuration (name, tableName, schema).
1530
+ - `resource.name` — The resource name.
1531
+ - `resource.tableName` — The database table name for users.
1532
+ - `resource.schema` — The validation schema for user properties.
1533
+
1534
+ **Returns:** A request handler for two-factor authentication operations.
1535
+
1536
+ #### `types`
1537
+
1538
+ Re-exported as a namespace — reach every member below through it (e.g. `types.<name>`).
1539
+
1540
+ ##### `types.Props`
1541
+
1542
+ User props type inferred from schema.
1543
+
1544
+ ```typescript
1545
+ type Props = z.infer<typeof propsSchema>
1546
+ ```
1547
+
1548
+ ##### `types.SecretProps`
1549
+
1550
+ Secret Props type.
1551
+
1552
+ ```typescript
1553
+ type SecretProps = z.infer<typeof secretPropsSchema>
1554
+ ```
1555
+
1556
+ ##### `types.CreateProps`
1557
+
1558
+ Create Props type.
1559
+
1560
+ ```typescript
1561
+ type CreateProps = z.infer<typeof createPropsSchema>
1562
+ ```
1563
+
1564
+ ##### `types.CreateSecretProps`
1565
+
1566
+ Create Secret Props type.
1567
+
1568
+ ```typescript
1569
+ type CreateSecretProps = z.infer<typeof createSecretPropsSchema>
1570
+ ```
1571
+
1572
+ ##### `types.CreateOAuthProps`
1573
+
1574
+ Create O Auth Props type.
1575
+
1576
+ ```typescript
1577
+ type CreateOAuthProps = z.infer<typeof createOAuthPropsSchema>
1578
+ ```
1579
+
1580
+ ##### `types.UpdateProps`
1581
+
1582
+ Update Props type.
1583
+
1584
+ ```typescript
1585
+ type UpdateProps = z.infer<typeof updatePropsSchema>
1586
+ ```
1587
+
1588
+ ##### `types.UpdatePasswordSecretProps`
1589
+
1590
+ Update Password Secret Props type.
1591
+
1592
+ ```typescript
1593
+ type UpdatePasswordSecretProps = z.infer<typeof updatePasswordSecretPropsSchema>
1594
+ ```
1595
+
1596
+ ##### `types.UpdatePlanProps`
1597
+
1598
+ Update Plan Props type.
1599
+
1600
+ ```typescript
1601
+ type UpdatePlanProps = z.infer<typeof updatePlanPropsSchema>
1602
+ ```
1603
+
1604
+ ##### `types.VerifyTwoFactorProps`
1605
+
1606
+ Verify Two Factor Props type.
1607
+
1608
+ ```typescript
1609
+ type VerifyTwoFactorProps = z.infer<typeof verifyTwoFactorPropsSchema>
1610
+ ```
1611
+
1612
+ ##### `types.VerifyTwoFactorSecretProps`
1613
+
1614
+ Verify Two Factor Secret Props type.
1615
+
1616
+ ```typescript
1617
+ type VerifyTwoFactorSecretProps = z.infer<typeof verifyTwoFactorSecretPropsSchema>
1618
+ ```
1619
+
1620
+ ##### `types.Session`
1621
+
1622
+ User session data (userId, email, role, permissions, metadata) inferred from sessionSchema.
1623
+
1624
+ ```typescript
1625
+ type Session = z.infer<typeof sessionSchema>
1626
+ ```
1627
+
1628
+ ##### `types.Resource`
1629
+
1630
+ An object describing the `user` resource.
1631
+
1632
+ ```typescript
1633
+ type Resource<T = unknown> = resourceTypes.Resource<T>
1634
+ ```
1635
+
1636
+ #### `utilities`
1637
+
1638
+ Re-exported as a namespace — reach every member below through it (e.g. `utilities.<name>`).
1639
+
1640
+ ##### `utilities.fetchAvatarDataUri(url)`
1641
+
1642
+ Downloads an OAuth provider's profile image and re-hosts it as an inline
1643
+ `data:` URI so the stored avatar never references a third-party domain
1644
+ (provider URLs expire, and hot-linking leaks every viewer's request to the
1645
+ provider's CDN).
1646
+
1647
+ Best-effort by design: any refusal or failure — non-https URL, private or
1648
+ unresolvable host, timeout, non-image content type, oversized body — returns
1649
+ `undefined` (logged at debug) so OAuth login/creation never fails over an
1650
+ avatar.
1651
+
1652
+ ```typescript
1653
+ function fetchAvatarDataUri(url: string): Promise<string | undefined>
1654
+ ```
1655
+
1656
+ - `url` — The provider profile-image URL (`OAuthUserProps.avatar`).
1657
+
1658
+ **Returns:** The image as a `data:` URI within {@link MAX_AVATAR_LENGTH}, or `undefined`.
1659
+
1660
+ ##### `utilities.getPlan(user)`
1661
+
1662
+ Get a user's current plan info.
1663
+ Uses the bonded PlanService if available.
1664
+
1665
+ ```typescript
1666
+ function getPlan(user: {
1667
+ id: string
1668
+ createdAt: string
1669
+ updatedAt: string
1670
+ username?: string | undefined
1671
+ name?: string | undefined
1672
+ email?: string | null | undefined
1673
+ emailVerified?: boolean | undefined
1674
+ avatar?: string | null | undefined
1675
+ bio?: string | null | undefined
1676
+ twoFactorEnabled?: boolean | undefined
1677
+ oauthServer?: string | undefined
1678
+ oauthId?: string | undefined
1679
+ oauthData?: Record<string, unknown> | undefined
1680
+ planKey?: string | undefined
1681
+ planExpiresAt?: string | undefined
1682
+ planAutoRenews?: boolean | undefined
1683
+ }): Promise<Plan | PlanInfo | null>
1684
+ ```
1685
+
1686
+ - `user` — The user props (needs `planKey`, `planExpiresAt`, `planAutoRenews`).
1687
+
1688
+ **Returns:** The user's plan info with expiration status, or `null` if no `PlanService` is bonded.
1689
+
1690
+ ##### `utilities.invalidateEntitlementsCache(userId)`
1691
+
1692
+ Invalidates the entitlements plan-key cache for a user after their plan
1693
+ changed (paid upgrade via `verifyPayment`, webhook grant/cancellation via
1694
+ `handlePaymentNotification`, admin `updatePlan`).
1695
+
1696
+ `@molecule/api-entitlements` caches each user's effective plan key for its
1697
+ TTL (default 5 minutes) on the `getEffectiveTier` hot path. Without this
1698
+ call, a user who just PAID keeps seeing their old (free) tier — and a
1699
+ canceled user keeps premium — until the TTL lapses. The dependency is an
1700
+ OPTIONAL peer: apps that don't use entitlements simply have nothing to
1701
+ invalidate, so the import failure is a documented no-op.
1702
+
1703
+ ```typescript
1704
+ function invalidateEntitlementsCache(userId: string): Promise<void>
1705
+ ```
1706
+
1707
+ - `userId` — The user whose cached plan key must be dropped.
1708
+
1709
+ ##### `utilities.invalidateEntitlementsCacheSafe(userId)`
1710
+
1711
+ Fire-and-forget variant of {@link invalidateEntitlementsCache} for call
1712
+ sites that must not await (or fail) the surrounding response on cache
1713
+ maintenance.
1714
+
1715
+ ```typescript
1716
+ function invalidateEntitlementsCacheSafe(userId: string): void
1717
+ ```
1718
+
1719
+ - `userId` — The user whose cached plan key must be dropped.
1720
+
1721
+ ##### `utilities.normalizeEmail(email)`
1722
+
1723
+ Normalizes an email address for storage and lookup so case/whitespace
1724
+ variants of the same mailbox cannot bypass the `email` UNIQUE constraint
1725
+ (e.g. `Foo@Example.com` vs `foo@example.com`).
1726
+
1727
+ Trims surrounding whitespace and lowercases the whole address. While the
1728
+ local-part is technically case-sensitive per RFC 5321, every mainstream
1729
+ provider treats it case-insensitively, and the account-takeover risk of
1730
+ allowing variants far outweighs that pedantry. Both the local signup
1731
+ (`create`) and OAuth (`logInOAuth`) write paths MUST use this so the stored
1732
+ column and every collision lookup compare apples to apples.
1733
+
1734
+ ```typescript
1735
+ function normalizeEmail(email: string | null | undefined): string | undefined
1736
+ ```
1737
+
1738
+ - `email` — The raw email address (or null/undefined).
1739
+
1740
+ **Returns:** The normalized email, or `undefined` when the input is empty/blank.
1741
+
1742
+ ##### `utilities.notify(options)`
1743
+
1744
+ Sends push notifications to all of a user's devices except the current one. Retrieves devices
1745
+ with active push subscriptions via the bonded DeviceService, then sends each notification via
1746
+ `@molecule/api-push-notifications`. Silently no-ops if either dependency is unavailable.
1747
+
1748
+ ```typescript
1749
+ function notify({
1750
+ userId,
1751
+ deviceId,
1752
+ title,
1753
+ titleKey,
1754
+ body,
1755
+ bodyKey,
1756
+ }: {
1757
+ userId: string
1758
+ deviceId?: string
1759
+ title: string
1760
+ titleKey?: string
1761
+ body: string
1762
+ bodyKey?: string
1763
+ }): Promise<void>
1764
+ ```
1765
+
1766
+ - `options` — Notification options.
1767
+ - `options.userId` — The user whose devices should receive the notification.
1768
+ - `options.deviceId` — The current device ID to exclude from notifications.
1769
+ - `options.title` — The notification title text.
1770
+ - `options.titleKey` — The i18n key for the title (sent as notification data for client-side localization).
1771
+ - `options.body` — The notification body text.
1772
+ - `options.bodyKey` — The i18n key for the body (sent as notification data for client-side localization).
1773
+
1774
+ ##### `utilities.SENSITIVE_USER_COLUMNS`
1775
+
1776
+ User-row columns that must never appear in a self-read response.
1777
+
1778
+ ```typescript
1779
+ const SENSITIVE_USER_COLUMNS: readonly [
1780
+ 'oauthData',
1781
+ 'oauthId',
1782
+ 'emailConfirmationToken',
1783
+ 'emailConfirmationTokenAt',
1784
+ 'passwordResetToken',
1785
+ 'passwordResetTokenAt',
1786
+ 'passwordHash',
1787
+ 'twoFactorSecret',
1788
+ 'pendingTwoFactorSecret',
1789
+ 'anonymousSecretHash',
1790
+ 'anonymousSecret',
1791
+ 'stripeCustomerId',
1792
+ ]
1793
+ ```
1794
+
1795
+ ##### `utilities.stripSensitiveUserColumns(user)`
1796
+
1797
+ Returns a shallow copy of a user row with {@link SENSITIVE_USER_COLUMNS}
1798
+ removed. The input row is not mutated.
1799
+
1800
+ ```typescript
1801
+ function stripSensitiveUserColumns(user: T): T
1802
+ ```
1803
+
1804
+ - `user` — The full user row (as loaded by `findById`).
1805
+
1806
+ **Returns:** A copy of the row without secret columns.
1807
+
1808
+ ##### `utilities.USERNAME_RE`
1809
+
1810
+ What a username may hold: letters, digits, dots, hyphens and underscores, starting with
1811
+ a letter or digit. A signup or profile update with anything else is refused rather than
1812
+ rewritten, so the stored username is always the one the user typed.
1813
+
1814
+ ```typescript
1815
+ const USERNAME_RE: RegExp
1816
+ ```
1817
+
1818
+ ##### `utilities.USERNAME_STRIP_RE`
1819
+
1820
+ The characters a username may not hold, for deriving one from a provider handle.
1821
+
1822
+ ```typescript
1823
+ const USERNAME_STRIP_RE: RegExp
1824
+ ```
1825
+
1826
+ ##### `utilities.isNestedBody(body)`
1827
+
1828
+ Whether a request body carries its signup fields under a `user` key
1829
+ (`{ user: { username, password } }`) instead of at the top level.
1830
+
1831
+ ```typescript
1832
+ function isNestedBody(body: unknown): boolean
1833
+ ```
1834
+
1835
+ - `body` — The request body.
591
1836
 
592
- Members:
593
-
594
- - `z.core` — namespace
595
- - `z.infer` — type
596
- - `z.output` — type
597
- - `z.input` — type
598
- - `z.JSONType` — type
599
- - `z.globalRegistry` — const
600
- - `z.GlobalMeta` — interface
601
- - `z.registry` — function
602
- - `z.config` — function
603
- - `z.$output` — const
604
- - `z.$input` — const
605
- - `z.$brand` — const
606
- - `z.clone` — function
607
- - `z.regexes` — namespace
608
- - `z.treeifyError` — function
609
- - `z.prettifyError` — function
610
- - `z.formatError` — function
611
- - `z.flattenError` — function
612
- - `z.TimePrecision` — const
613
- - `z.util` — namespace
614
- - `z.NEVER` — const: A special constant with type `never`
615
- - `z.toJSONSchema` — function
616
- - `z.fromJSONSchema` — function: Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change.
617
- - `z.locales` — namespace
618
- - `z.ZodISODateTime` — interface
619
- - `z.ZodISODate` — interface
620
- - `z.ZodISOTime` — interface
621
- - `z.ZodISODuration` — interface
622
- - `z.iso` — namespace
623
- - `z.ZodCoercedString` — interface
624
- - `z.ZodCoercedNumber` — interface
625
- - `z.ZodCoercedBigInt` — interface
626
- - `z.ZodCoercedBoolean` — interface
627
- - `z.ZodCoercedDate` — interface
628
- - `z.coerce` — namespace
629
- - `z.string` — function
630
- - `z.email` — function
631
- - `z.guid` — function
632
- - `z.uuid` — function
633
- - `z.uuidv4` — function
634
- - `z.uuidv6` — function
635
- - `z.uuidv7` — function
636
- - `z.url` — function
637
- - `z.httpUrl` — function
638
- - `z.emoji` — function
639
- - `z.nanoid` — function
640
- - `z.cuid` — function: Validates a CUID v1 string.
641
- - `z.cuid2` — function
642
- - `z.ulid` — function
643
- - `z.xid` — function
644
- - `z.ksuid` — function
645
- - `z.ipv4` — function
646
- - `z.mac` — function
647
- - `z.ipv6` — function
648
- - `z.cidrv4` — function
649
- - `z.cidrv6` — function
650
- - `z.base64` — function
651
- - `z.base64url` — function
652
- - `z.e164` — function
653
- - `z.jwt` — function
654
- - `z.stringFormat` — function
655
- - `z.hostname` — function
656
- - `z.hex` — function
657
- - `z.hash` — function
658
- - `z.number` — function
659
- - `z.int` — function
660
- - `z.float32` — function
661
- - `z.float64` — function
662
- - `z.int32` — function
663
- - `z.uint32` — function
664
- - `z.boolean` — function
665
- - `z.bigint` — function
666
- - `z.int64` — function
667
- - `z.uint64` — function
668
- - `z.symbol` — function
669
- - `z.any` — function
670
- - `z.unknown` — function
671
- - `z.never` — function
672
- - `z.date` — function
673
- - `z.array` — function
674
- - `z.keyof` — function
675
- - `z.object` — function
676
- - `z.strictObject` — function
677
- - `z.looseObject` — function
678
- - `z.union` — function
679
- - `z.xor` — function: Creates an exclusive union (XOR) where exactly one option must match.
680
- - `z.discriminatedUnion` — function
681
- - `z.intersection` — function
682
- - `z.tuple` — function
683
- - `z.record` — function
684
- - `z.partialRecord` — function
685
- - `z.looseRecord` — function
686
- - `z.map` — function
687
- - `z.set` — function
688
- - `z.nativeEnum` — function
689
- - `z.literal` — function
690
- - `z.file` — function
691
- - `z.transform` — function
692
- - `z.optional` — function
693
- - `z.exactOptional` — function
694
- - `z.nullable` — function
695
- - `z.nullish` — function
696
- - `z._default` — function
697
- - `z.prefault` — function
698
- - `z.nonoptional` — function
699
- - `z.success` — function
700
- - `z.nan` — function
701
- - `z.pipe` — function
702
- - `z.codec` — function
703
- - `z.invertCodec` — function
704
- - `z.readonly` — function
705
- - `z.templateLiteral` — function
706
- - `z.lazy` — function
707
- - `z.promise` — function
708
- - `z._function` — function
709
- - `z.check` — function
710
- - `z.custom` — function
711
- - `z.refine` — function
712
- - `z.superRefine` — function
713
- - `z.json` — function
714
- - `z.preprocess` — function
715
- - `z.ZodStandardSchemaWithJSON` — type
716
- - `z.ZodType` — interface
717
- - `z._ZodType` — interface
718
- - `z._ZodString` — interface
719
- - `z.ZodString` — interface
720
- - `z.ZodStringFormat` — interface
721
- - `z.ZodEmail` — interface
722
- - `z.ZodGUID` — interface
723
- - `z.ZodUUID` — interface
724
- - `z.ZodURL` — interface
725
- - `z.ZodEmoji` — interface
726
- - `z.ZodNanoID` — interface
727
- - `z.ZodCUID` — interface
728
- - `z.ZodCUID2` — interface
729
- - `z.ZodULID` — interface
730
- - `z.ZodXID` — interface
731
- - `z.ZodKSUID` — interface
732
- - `z.ZodIPv4` — interface
733
- - `z.ZodMAC` — interface
734
- - `z.ZodIPv6` — interface
735
- - `z.ZodCIDRv4` — interface
736
- - `z.ZodCIDRv6` — interface
737
- - `z.ZodBase64` — interface
738
- - `z.ZodBase64URL` — interface
739
- - `z.ZodE164` — interface
740
- - `z.ZodJWT` — interface
741
- - `z.ZodCustomStringFormat` — interface
742
- - `z._ZodNumber` — interface
743
- - `z.ZodNumber` — interface
744
- - `z.ZodNumberFormat` — interface
745
- - `z.ZodInt` — interface
746
- - `z.ZodFloat32` — interface
747
- - `z.ZodFloat64` — interface
748
- - `z.ZodInt32` — interface
749
- - `z.ZodUInt32` — interface
750
- - `z._ZodBoolean` — interface
751
- - `z.ZodBoolean` — interface
752
- - `z._ZodBigInt` — interface
753
- - `z.ZodBigInt` — interface
754
- - `z.ZodBigIntFormat` — interface
755
- - `z.ZodSymbol` — interface
756
- - `z.ZodUndefined` — interface
757
- - `z.undefined` — function
758
- - `z.ZodNull` — interface
759
- - `z.null` — function
760
- - `z.ZodAny` — interface
761
- - `z.ZodUnknown` — interface
762
- - `z.ZodNever` — interface
763
- - `z.ZodVoid` — interface
764
- - `z.void` — function
765
- - `z._ZodDate` — interface
766
- - `z.ZodDate` — interface
767
- - `z.ZodArray` — interface
768
- - `z.SafeExtendShape` — type
769
- - `z.ZodObject` — interface
770
- - `z.ZodUnion` — interface
771
- - `z.ZodXor` — interface
772
- - `z.ZodDiscriminatedUnion` — interface
773
- - `z.ZodIntersection` — interface
774
- - `z.ZodTuple` — interface
775
- - `z.ZodRecord` — interface
776
- - `z.ZodMap` — interface
777
- - `z.ZodSet` — interface
778
- - `z.ZodEnum` — interface
779
- - `z.enum` — function
780
- - `z.ZodLiteral` — interface
781
- - `z.ZodFile` — interface
782
- - `z.ZodTransform` — interface
783
- - `z.ZodOptional` — interface
784
- - `z.ZodExactOptional` — interface
785
- - `z.ZodNullable` — interface
786
- - `z.ZodDefault` — interface
787
- - `z.ZodPrefault` — interface
788
- - `z.ZodNonOptional` — interface
789
- - `z.ZodSuccess` — interface
790
- - `z.ZodCatch` — interface
791
- - `z.catch` — function
792
- - `z.ZodNaN` — interface
793
- - `z.ZodPipe` — interface
794
- - `z.ZodCodec` — interface
795
- - `z.ZodPreprocess` — interface
796
- - `z.ZodReadonly` — interface
797
- - `z.ZodTemplateLiteral` — interface
798
- - `z.ZodLazy` — interface
799
- - `z.ZodPromise` — interface
800
- - `z.ZodFunction` — interface
801
- - `z.function` — function
802
- - `z.ZodCustom` — interface
803
- - `z.describe` — const
804
- - `z.meta` — const
805
- - `z.instanceof` — function
806
- - `z.stringbool` — const
807
- - `z.ZodJSONSchemaInternals` — interface
808
- - `z.ZodJSONSchema` — interface
809
- - `z.lt` — function
810
- - `z.lte` — function
811
- - `z.gt` — function
812
- - `z.gte` — function
813
- - `z.positive` — function
814
- - `z.negative` — function
815
- - `z.nonpositive` — function
816
- - `z.nonnegative` — function
817
- - `z.multipleOf` — function
818
- - `z.maxSize` — function
819
- - `z.minSize` — function
820
- - `z.size` — function
821
- - `z.maxLength` — function
822
- - `z.minLength` — function
823
- - `z.length` — function
824
- - `z.regex` — function
825
- - `z.lowercase` — function
826
- - `z.uppercase` — function
827
- - `z.includes` — function
828
- - `z.startsWith` — function
829
- - `z.endsWith` — function
830
- - `z.property` — function
831
- - `z.mime` — function
832
- - `z.overwrite` — function
833
- - `z.normalize` — function
834
- - `z.trim` — function
835
- - `z.toLowerCase` — function
836
- - `z.toUpperCase` — function
837
- - `z.slugify` — function
838
- - `z.RefinementCtx` — interface
839
- - `z.ZodIssue` — type
840
- - `z.ZodError` — interface: An Error-like class used to store Zod validation issues.
841
- - `z.ZodRealError` — const
842
- - `z.ZodFlattenedError` — type
843
- - `z.ZodFormattedError` — type
844
- - `z.ZodErrorMap` — interface
845
- - `z.IssueData` — type
846
- - `z.ZodSafeParseResult` — type
847
- - `z.ZodSafeParseSuccess` — type
848
- - `z.ZodSafeParseError` — type
849
- - `z.parse` — const
850
- - `z.parseAsync` — const
851
- - `z.safeParse` — const
852
- - `z.safeParseAsync` — const
853
- - `z.encode` — const
854
- - `z.decode` — const
855
- - `z.encodeAsync` — const
856
- - `z.decodeAsync` — const
857
- - `z.safeEncode` — const
858
- - `z.safeDecode` — const
859
- - `z.safeEncodeAsync` — const
860
- - `z.safeDecodeAsync` — const
861
- - `z.setErrorMap` — function
862
- - `z.getErrorMap` — function
863
- - `z.TypeOf` — type
864
- - `z.Infer` — type
865
- - `z.ZodFirstPartySchemaTypes` — type
866
- - `z.ZodIssueCode` — const
867
- - `z.inferFlattenedErrors` — type
868
- - `z.inferFormattedError` — type
869
- - `z.BRAND` — type: Use `z.$brand` instead
870
- - `z.ZodTypeAny` — interface
871
- - `z.ZodSchema` — interface
872
- - `z.Schema` — interface
873
- - `z.ZodRawShape` — type: Included for Zod 3 compatibility
874
- - `z.ZodFirstPartyTypeKind` — enum
1837
+ **Returns:** True when the fields are nested under `user`.
875
1838
 
876
1839
  ## Injection Notes
877
1840
 
@@ -948,7 +1911,21 @@ and `Authorization: Token <jwt>` (RealWorld's scheme), but only for a token whos
948
1911
  `deviceId` names an ACTIVE row in `devices`. A JWT you `sign()` with an invented `deviceId`
949
1912
  is answered 401 on every route. Mint sessions the way the built-in login does — create the
950
1913
  device with `get('device').createOrUpdate(userId, deviceName)` (it returns the device id; or call
951
- `authorization.set(…)`) and sign that id — instead of inventing one.
1914
+ `authorization.set(…)`) and sign that id — instead of inventing one. Return the user
1915
+ through `utilities.stripSensitiveUserColumns(row)` so no secret column reaches the client.
1916
+
1917
+ **A different wire format** (RealWorld's `{ user: { … } }`): the route handlers read a
1918
+ FLAT body (`req.body.username`, `req.body.password`) and are not a wire-format adapter —
1919
+ a nested body is answered 400 `user.error.bodyNestedUnderUser`. Unwrap the envelope
1920
+ before calling a handler, or write the route yourself. A username keeps exactly what was
1921
+ sent (letters, digits, `.`, `-`, `_`); anything else is answered 400
1922
+ `user.error.usernameInvalid`, never rewritten.
1923
+
1924
+ **A token-only JSON API:** `verifyMiddleware()` also accepts the `token` cookie that
1925
+ login sets, so a client that keeps a cookie jar (an HTTP test runner, `curl -b`) is
1926
+ still signed in on a request that sends no `Authorization` header, and gets 200 where a
1927
+ spec expects 401. Mount `verifyMiddleware({ allowCookieSession: false })` for an API
1928
+ whose clients send the header.
952
1929
 
953
1930
  **Revoking a session yourself:** the middleware caches "this device exists" for 10 s per
954
1931
  process, so a hand-written logout that deletes the `devices` row keeps authorizing that