@molecule/api-resource-user 1.5.7 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +291 -57
  2. package/dist/authorization.d.ts +64 -6
  3. package/dist/authorization.d.ts.map +1 -1
  4. package/dist/authorization.js +129 -17
  5. package/dist/authorization.js.map +1 -1
  6. package/dist/handlers/create.d.ts +19 -5
  7. package/dist/handlers/create.d.ts.map +1 -1
  8. package/dist/handlers/create.js +20 -5
  9. package/dist/handlers/create.js.map +1 -1
  10. package/dist/handlers/del.d.ts +2 -2
  11. package/dist/handlers/del.d.ts.map +1 -1
  12. package/dist/handlers/del.js +1 -1
  13. package/dist/handlers/del.js.map +1 -1
  14. package/dist/handlers/forgotPassword.d.ts +2 -2
  15. package/dist/handlers/forgotPassword.d.ts.map +1 -1
  16. package/dist/handlers/forgotPassword.js +2 -2
  17. package/dist/handlers/forgotPassword.js.map +1 -1
  18. package/dist/handlers/logIn.d.ts +13 -6
  19. package/dist/handlers/logIn.d.ts.map +1 -1
  20. package/dist/handlers/logIn.js +13 -6
  21. package/dist/handlers/logIn.js.map +1 -1
  22. package/dist/handlers/logInOAuth.d.ts +8 -4
  23. package/dist/handlers/logInOAuth.d.ts.map +1 -1
  24. package/dist/handlers/logInOAuth.js +9 -5
  25. package/dist/handlers/logInOAuth.js.map +1 -1
  26. package/dist/handlers/payments/handlePaymentNotification.d.ts +2 -2
  27. package/dist/handlers/payments/handlePaymentNotification.d.ts.map +1 -1
  28. package/dist/handlers/payments/handlePaymentNotification.js +2 -2
  29. package/dist/handlers/payments/handlePaymentNotification.js.map +1 -1
  30. package/dist/handlers/payments/verifyPayment.d.ts +2 -2
  31. package/dist/handlers/payments/verifyPayment.d.ts.map +1 -1
  32. package/dist/handlers/payments/verifyPayment.js +1 -1
  33. package/dist/handlers/payments/verifyPayment.js.map +1 -1
  34. package/dist/handlers/read.d.ts +2 -2
  35. package/dist/handlers/read.d.ts.map +1 -1
  36. package/dist/handlers/read.js +1 -1
  37. package/dist/handlers/read.js.map +1 -1
  38. package/dist/handlers/readSelf.d.ts +10 -3
  39. package/dist/handlers/readSelf.d.ts.map +1 -1
  40. package/dist/handlers/readSelf.js +16 -2
  41. package/dist/handlers/readSelf.js.map +1 -1
  42. package/dist/handlers/resetPassword.d.ts +2 -1
  43. package/dist/handlers/resetPassword.d.ts.map +1 -1
  44. package/dist/handlers/resetPassword.js +2 -1
  45. package/dist/handlers/resetPassword.js.map +1 -1
  46. package/dist/handlers/update.d.ts +10 -4
  47. package/dist/handlers/update.d.ts.map +1 -1
  48. package/dist/handlers/update.js +10 -4
  49. package/dist/handlers/update.js.map +1 -1
  50. package/dist/handlers/updatePassword.d.ts +12 -3
  51. package/dist/handlers/updatePassword.d.ts.map +1 -1
  52. package/dist/handlers/updatePassword.js +25 -7
  53. package/dist/handlers/updatePassword.js.map +1 -1
  54. package/dist/handlers/updatePlan.d.ts +2 -2
  55. package/dist/handlers/updatePlan.d.ts.map +1 -1
  56. package/dist/handlers/updatePlan.js +1 -1
  57. package/dist/handlers/updatePlan.js.map +1 -1
  58. package/dist/handlers/verifyTwoFactor.d.ts +2 -2
  59. package/dist/handlers/verifyTwoFactor.d.ts.map +1 -1
  60. package/dist/handlers/verifyTwoFactor.js +2 -2
  61. package/dist/handlers/verifyTwoFactor.js.map +1 -1
  62. package/dist/index.d.ts +95 -14
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +95 -14
  65. package/dist/index.js.map +1 -1
  66. package/dist/types.d.ts +38 -0
  67. package/dist/types.d.ts.map +1 -1
  68. package/package.json +1 -1
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-17T19:21:12.007Z
6
+ Generated: 2026-10-19T22:44:43.616Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-resource-user
@@ -18,22 +18,19 @@ The `user` resource types, schema, and definition.
18
18
  - `usersSecrets` — {@link SecretProps}: `passwordHash`, `passwordResetToken` (and
19
19
  `passwordResetTokenAt`), `twoFactorSecret` / `pendingTwoFactorSecret`, `lastTwoFactorTimeStep`.
20
20
 
21
- **Table setup:** `src/__setup__/users.sql` + `src/__setup__/usersSecrets.sql`; an mlcl-scaffolded API replays `__setup__/*.sql` on migrate, anywhere else run them once.
21
+ **Table setup:** `src/__setup__/users.sql` + `src/__setup__/usersSecrets.sql`; an mlcl-scaffolded API replays `__setup__/*.sql` on migrate.
22
22
 
23
23
  **`usersSecrets.id` IS the user's id — the value of `users.id`, never a fresh uuid.** The DDL
24
- declares it `UNIQUE PRIMARY KEY` with no foreign key, so nothing enforces the pairing: a row
25
- written under another id is never found again — login answers "invalid credentials" while
26
- `GET /api/users/me` (which reads `users` only) still answers 200. A hand-written signup writes
27
- both rows from one id:
24
+ declares it `UNIQUE PRIMARY KEY` with no foreign key, so nothing enforces it: a row written
25
+ under another id is never found again — login answers "invalid credentials" while
26
+ `GET /api/users/me` still answers 200. A hand-written signup writes both rows:
28
27
  `const id = uuid(); await create('users', { ...props, id }); await create('usersSecrets', { id, passwordHash: await hash(password) })`.
29
28
 
30
- Prefer not to hand-write any of that: the handlers this package ships already do it —
31
- `handlers.create` (signup: writes both rows, hashes with `@molecule/api-password`, mints the
32
- session device), `handlers.logIn` (login: reads `usersSecrets` by the user's id and compares the
33
- hash), `handlers.updatePassword`, and `handlers.forgotPassword` / `handlers.resetPassword` (the
34
- emailed-token reset). To read or write one secret yourself, use the abstract datastore on the
35
- same key — `findById('usersSecrets', userId)`, or `${tableName}Secrets` when the resource
36
- carries a custom `tableName` — never SQL.
29
+ Prefer not to hand-write that — `handlers.create` (signup: both rows, hash via
30
+ `@molecule/api-password`, session device), `handlers.logIn` (reads `usersSecrets` by the user's
31
+ id), `handlers.updatePassword`, `handlers.forgotPassword` / `handlers.resetPassword`. To touch
32
+ one secret yourself use the datastore on the same key — `findById('usersSecrets', userId)` (or
33
+ `${tableName}Secrets` for a custom `tableName`) — never SQL.
37
34
 
38
35
  **Issuing a session yourself (the sequence is device, then session — two calls, and the first
39
36
  RETURNS the id):** the middleware accepts both `Authorization: Bearer <jwt>` and
@@ -53,8 +50,14 @@ const token = authorization.set(req, res, { userId, deviceId })
53
50
  `get<DeviceService>('device')` is the typed accessor (never hand-type a
54
51
  `get<{ createOrUpdate(): … }>('device')` generic: a wrong one still compiles and leaves the
55
52
  field you invented — `device.id` — `undefined`), and `createOrUpdate` RESOLVES TO THE DEVICE ID
56
- STRING, not to a row. `authorization.set()` throws when `deviceId` is missing rather than mint a
57
- token every later request answers 401.
53
+ STRING, not to a row. `set()` throws when `deviceId` is missing rather than mint a token every
54
+ later request answers 401.
55
+
56
+ **RealWorld-style token API (`Authorization: Token <jwt>`)? CONFIGURATION on this same auth
57
+ path — never a credentials table of your own** (`usersSecrets.passwordHash` is the password
58
+ store). Set `AUTH_SCHEME=Token` (or `verifyMiddleware({ scheme: 'Token' })`): every route
59
+ accepts it, `logIn`/`create` return `accessToken`, `GET /users/me` echoes it, and a password
60
+ change revokes every OTHER device but keeps the caller's own session.
58
61
 
59
62
  **`handlers.*` return `{ statusCode, headers?, body }` and never write to `res`** — not through
60
63
  `res.json`, not through `res.send`, not through `res.end`. The mounted routes apply that object
@@ -70,6 +73,65 @@ res.status(statusCode).send(body)
70
73
  Monkey-patching `res.json` to re-shape a handler's answer intercepts nothing the handler
71
74
  produces, so the request it was meant to answer is left unanswered and hangs.
72
75
 
76
+ **Re-shaping a success answer (RealWorld's `{ user: { …, token } }`, say)? Read the token from
77
+ `result.body.accessToken` — it is in the BODY.** The `Authorization` response header carries
78
+ the same token prefixed with the mount's scheme (`Bearer <token>`), so it is not the raw value
79
+ a client sends back. Type the result from the handler — do not cast `body` to `unknown`, which
80
+ hides the success branch — and narrow on the body's own keys:
81
+
82
+ ```typescript
83
+ const result = await handlers.logIn(resource)(req, res)
84
+ if (!('accessToken' in result.body)) {
85
+ // 400/403/500 `{ error, errorKey }`, or 206 `{ twoFactorRequired: true }` — send as built.
86
+ res.status(result.statusCode).send(result.body)
87
+ return
88
+ }
89
+ // `props` and `user` are the SAFE columns (secret columns stripped); accessToken is the token.
90
+ const { props, accessToken } = result.body
91
+ res.status(200).json({ user: { ...props, token: accessToken } })
92
+ ```
93
+
94
+ **Constructing a handler: `schema` is optional.** Every factory accepts
95
+ `{ name, tableName, schema? }`. `schema` is a Zod object (anything exposing `safeParse`)
96
+ and only `handlers.create` / `handlers.logInOAuth` use it — both default to this package's
97
+ `propsSchema`. `handlers.update` validates with its own update schema; login and the
98
+ read/write handlers never validate props. The smallest correct wiring, with every import
99
+ spelled out:
100
+
101
+ ```typescript
102
+ import { createRequestHandler } from '@molecule/api-resource'
103
+ import { createResource, handlers } from '@molecule/api-resource-user'
104
+
105
+ // Omit `schema`: create() validates new users with this package's propsSchema.
106
+ const signUp = createRequestHandler(handlers.create({ name: 'User', tableName: 'users' }))
107
+ const signIn = createRequestHandler(handlers.logIn({ name: 'User', tableName: 'users' }))
108
+
109
+ // A constrained schema, when the app restricts oauthServer / planKey.
110
+ const users = createResource({ oauthServers: ['google', 'github'] as const })
111
+ const signUpConstrained = createRequestHandler(handlers.create(users))
112
+ ```
113
+
114
+ `schema: {}` (or any object without `safeParse`) is NOT a schema: the first request
115
+ answers 400 `resource.error.unknownError` with
116
+ `TypeError: schema.safeParse is not a function`, and no row is written. Omit `schema`
117
+ instead of stubbing it.
118
+
119
+ **Exact responses of the sign-up and sign-in handlers** (the body shapes the routes send;
120
+ a handler returns `{ statusCode, body }` and the mount applies it):
121
+
122
+ - `create` (`POST /api/users`, flat body): 201 `{ props, accessToken, user }` (`user` equals
123
+ `props`, secret columns stripped); 400 `user.error.usernameInvalid` /
124
+ `user.error.bodyNestedUnderUser` / `user.error.passwordRequired` /
125
+ `user.error.passwordTooLong` / `user.error.passwordTooShort` / `user.error.emailInvalid` /
126
+ `user.error.badRequest`, or `resource.error.unknownError` when props fail the schema;
127
+ 403 `user.error.usernameUnavailable` / `user.error.emailAlreadyRegistered`;
128
+ 500 `user.error.failedToHashPassword` / `user.error.failedToCreateSession`.
129
+ - `logIn` (`POST /api/users/log-in`): 200 `{ props, accessToken, user }`; 206
130
+ `{ twoFactorRequired: true }`; 403 `user.error.invalidCredentials` /
131
+ `user.error.invalidTwoFactorToken`; 500 `user.error.failedToCreateSession` /
132
+ `user.error.twoFactorVerificationUnavailable` / `user.error.loginFailed`. Bad credentials
133
+ are 403, not 401 or 422.
134
+
73
135
  > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
74
136
  > It is written to be read by coding agents as much as by people, and is generated from this
75
137
  > package's source — edit `src/index.ts` JSDoc, not this file.
@@ -635,6 +697,59 @@ function getAuthCookieOptions(): {
635
697
 
636
698
  **Returns:** The environment-appropriate base cookie options.
637
699
 
700
+ ##### `authorization.DEFAULT_AUTH_SCHEME`
701
+
702
+ The `Authorization` scheme this resource uses when nothing configures another
703
+ one — the scheme {@link set} writes into the response header.
704
+
705
+ ```typescript
706
+ const DEFAULT_AUTH_SCHEME: 'Bearer'
707
+ ```
708
+
709
+ ##### `authorization.AUTH_SCHEME_LOCALS_KEY`
710
+
711
+ `res.locals` key carrying the `Authorization` scheme THIS request's mount uses:
712
+ `'Bearer'` by default, `'Token'` for a Django REST Framework / RealWorld-style
713
+ API. {@link verifyMiddleware} records it from its `scheme` option (or the app's
714
+ `AUTH_SCHEME`), and {@link set} reads it so a sign-in response labels its token
715
+ with the SAME scheme the client will send back. A `set()` call outside a request
716
+ (a handler invoked directly) falls back to `AUTH_SCHEME`, then to `Bearer`.
717
+
718
+ ```typescript
719
+ const AUTH_SCHEME_LOCALS_KEY: 'authScheme'
720
+ ```
721
+
722
+ ##### `authorization.AUTH_TOKEN_LOCALS_KEY`
723
+
724
+ `res.locals` key carrying the raw JWT that authenticated THIS request — written
725
+ ONLY when the request sent it in the `Authorization` header, never when the
726
+ session came from the httpOnly `token` cookie.
727
+
728
+ That asymmetry is deliberate: echoing a cookie-resolved token into a JSON body
729
+ would hand JavaScript the exact credential the cookie exists to keep unreadable
730
+ (an XSS exfiltration path). A header token is already in the client's hands, so
731
+ `GET /users/me` may return it as `accessToken` to a token-only client that
732
+ restores its session from that response.
733
+
734
+ ```typescript
735
+ const AUTH_TOKEN_LOCALS_KEY: 'authToken'
736
+ ```
737
+
738
+ ##### `authorization.getConfiguredAuthScheme()`
739
+
740
+ The app's configured `Authorization` scheme: `AUTH_SCHEME` from the environment,
741
+ defaulting to {@link DEFAULT_AUTH_SCHEME}.
742
+
743
+ Read at call time (not module load) so a process — or a test — that changes the
744
+ env sees the new value. A session-only app that never sets `AUTH_SCHEME` keeps
745
+ emitting `Bearer`.
746
+
747
+ ```typescript
748
+ function getConfiguredAuthScheme(): string
749
+ ```
750
+
751
+ **Returns:** A validated scheme name.
752
+
638
753
  ##### `authorization.invalidateDeviceExistsCache(deviceId)`
639
754
 
640
755
  Evict a single device's positive entry from the device-exists cache so the
@@ -790,19 +905,35 @@ interface VerifyMiddlewareOptions {
790
905
  * "no auth".
791
906
  */
792
907
  allowCookieSession?: boolean
908
+ /**
909
+ * The `Authorization` scheme this mount accepts and mints: `'Bearer'` (default), or
910
+ * `'Token'` for a Django REST Framework / RealWorld-style API. Defaults to the app's
911
+ * `AUTH_SCHEME` environment value.
912
+ *
913
+ * This is a LABEL, not a second auth mechanism: every route the mount covers accepts the
914
+ * same verifiable JWT, whether it arrives as `Bearer <jwt>` or `Token <jwt>` (both stay
915
+ * accepted). The option decides what {@link set} writes into the sign-in response header
916
+ * — and therefore what the client sends back and what its HTTP client must be configured
917
+ * with (`createFetchClient({ baseURL, authScheme: 'Token' })`).
918
+ */
919
+ scheme?: string
793
920
  }
794
921
  ```
795
922
 
796
923
  ##### `authorization.verifyMiddleware(options)`
797
924
 
798
925
  Middleware that verifies the JWT token from the `Authorization` header and sets `res.locals.session`.
799
- Falls back to cookie-based session for browser clients unless `allowCookieSession` is `false` — which also stops `set()` writing the session cookie for this request. Auto-refreshes tokens older than `JWT_REFRESH_TIME`.
926
+ Accepts `Bearer` and `Token` (Django REST / RealWorld) plus the configured scheme, on EVERY
927
+ route the mount covers. Falls back to cookie-based session for browser clients unless
928
+ `allowCookieSession` is `false` — which also stops `set()` writing the session cookie for this
929
+ request. Records the scheme for `set()` and, when the token came from the header, records the
930
+ raw token in `res.locals[AUTH_TOKEN_LOCALS_KEY]`. Auto-refreshes tokens older than `JWT_REFRESH_TIME`.
800
931
 
801
932
  ```typescript
802
933
  function verifyMiddleware(options?: VerifyMiddlewareOptions): MoleculeRequestHandler
803
934
  ```
804
935
 
805
- - `options` — {@link VerifyMiddlewareOptions} controlling the auto-refresh.
936
+ - `options` — {@link VerifyMiddlewareOptions} controlling the auto-refresh, cookie policy and scheme.
806
937
 
807
938
  **Returns:** An Express-compatible middleware function.
808
939
 
@@ -995,8 +1126,22 @@ Creates a user with username and password. Validates username uniqueness and ema
995
1126
  hashes the password into a separate secrets table, creates a session device via the bonded
996
1127
  DeviceService, and sets JWT authorization on the response.
997
1128
 
1129
+ **`schema` is optional — omit it and this package's `propsSchema` validates the row.**
1130
+ It must be a Zod object (anything exposing `safeParse`): pass
1131
+ `createResource({ oauthServers, planKeys })` or your own extended schema only when the
1132
+ app constrains or extends user props. A stub such as `schema: {}` is not a schema — the
1133
+ FIRST request answers 400 `resource.error.unknownError` with
1134
+ `TypeError: schema.safeParse is not a function`, after no row has been written.
1135
+
1136
+ Statuses: 201 `{ props, accessToken, user }`; 400 `user.error.usernameInvalid` /
1137
+ `user.error.bodyNestedUnderUser` / `user.error.passwordRequired` /
1138
+ `user.error.passwordTooLong` / `user.error.passwordTooShort` / `user.error.emailInvalid` /
1139
+ `user.error.badRequest`, or `resource.error.unknownError` when props fail the schema;
1140
+ 403 `user.error.usernameUnavailable` / `user.error.emailAlreadyRegistered`;
1141
+ 500 `user.error.failedToHashPassword` / `user.error.failedToCreateSession`.
1142
+
998
1143
  ```typescript
999
- function create({ name, tableName, schema }: types.Resource<unknown>): (
1144
+ function create({ name, tableName, schema = propsSchema }: types.HandlerResource): (
1000
1145
  req: CreateRequest,
1001
1146
  res: MoleculeResponse,
1002
1147
  ) => Promise<
@@ -1016,12 +1161,12 @@ function create({ name, tableName, schema }: types.Resource<unknown>): (
1016
1161
  >
1017
1162
  ```
1018
1163
 
1019
- - `resource` — The user resource configuration (name, tableName, schema).
1020
- - `resource.name` — The resource name.
1164
+ - `resource` — The user resource configuration: `{ name, tableName, schema? }`.
1165
+ - `resource.name` — The resource name used in error messages.
1021
1166
  - `resource.tableName` — The database table name for users.
1022
- - `resource.schema` — The validation schema for user properties.
1167
+ - `resource.schema` — Optional Zod schema for the created user props. Defaults to `propsSchema`.
1023
1168
 
1024
- **Returns:** A request handler that responds with `{ statusCode: 201, body: { props } }` on success.
1169
+ **Returns:** A request handler that responds with `{ statusCode: 201, body: { props, accessToken, user } }` on success.
1025
1170
 
1026
1171
  ##### `handlers.del(resource)`
1027
1172
 
@@ -1041,7 +1186,7 @@ function del({
1041
1186
  name: _name,
1042
1187
  tableName,
1043
1188
  schema: _schema,
1044
- }: types.Resource<unknown>): (
1189
+ }: types.HandlerResource): (
1045
1190
  req: MoleculeRequest,
1046
1191
  ) => Promise<
1047
1192
  | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
@@ -1052,7 +1197,7 @@ function del({
1052
1197
  - `resource` — The user resource configuration (name, tableName, schema).
1053
1198
  - `resource.name` — The resource name.
1054
1199
  - `resource.tableName` — The database table name for users.
1055
- - `resource.schema` — The validation schema for user properties.
1200
+ - `resource.schema` — Optional. Ignored — deletion does not validate props.
1056
1201
 
1057
1202
  **Returns:** A request handler that responds with `{ statusCode: 200, body: { props: { id } } }` on success.
1058
1203
 
@@ -1079,7 +1224,7 @@ function forgotPassword({
1079
1224
  name: _name,
1080
1225
  tableName,
1081
1226
  schema: _schema,
1082
- }: types.Resource<unknown>): (
1227
+ }: types.HandlerResource): (
1083
1228
  req: ForgotPasswordRequest,
1084
1229
  ) => Promise<
1085
1230
  | { statusCode: number; body: { error: string; errorKey: string; success?: undefined } }
@@ -1090,7 +1235,7 @@ function forgotPassword({
1090
1235
  - `resource` — The user resource configuration (name, tableName, schema).
1091
1236
  - `resource.name` — The resource name.
1092
1237
  - `resource.tableName` — The database table name for users.
1093
- - `resource.schema` — The validation schema for user properties.
1238
+ - `resource.schema` — Optional. Ignored — the reset flow reads and writes secrets directly.
1094
1239
 
1095
1240
  **Returns:** A request handler that responds with `{ statusCode: 200, body: { success: true } }`.
1096
1241
 
@@ -1118,8 +1263,15 @@ authentication (1-hour expiry), and optional two-factor verification via `@molec
1118
1263
  On success, creates/updates a device via the bonded DeviceService, sets JWT authorization,
1119
1264
  and notifies other devices about the new login.
1120
1265
 
1266
+ `schema` is optional and NOT used here: login reads stored rows and compares credentials, so
1267
+ there are no props to validate. Statuses: 200 `{ props, accessToken, user }`; 206
1268
+ `{ twoFactorRequired: true }` when the account has 2FA enabled and no `twoFactorToken` was
1269
+ sent; 403 `user.error.invalidCredentials` (wrong password / unknown account / spent reset
1270
+ token) or `user.error.invalidTwoFactorToken`; 500 `user.error.failedToCreateSession` /
1271
+ `user.error.twoFactorVerificationUnavailable` / `user.error.loginFailed`.
1272
+
1121
1273
  ```typescript
1122
- function logIn({ name: _name, tableName, schema: _schema }: types.Resource<unknown>): (
1274
+ function logIn({ tableName }: types.HandlerResource): (
1123
1275
  req: LogInRequest,
1124
1276
  res: MoleculeResponse,
1125
1277
  ) => Promise<
@@ -1159,12 +1311,12 @@ function logIn({ name: _name, tableName, schema: _schema }: types.Resource<unkno
1159
1311
  >
1160
1312
  ```
1161
1313
 
1162
- - `resource` — The user resource configuration (name, tableName, schema).
1163
- - `resource.name` — The resource name.
1314
+ - `resource` — The user resource configuration: `{ name, tableName, schema? }`.
1315
+ - `resource.name` — The resource name (unused by this handler).
1164
1316
  - `resource.tableName` — The database table name for users.
1165
- - `resource.schema` — The validation schema for user properties.
1317
+ - `resource.schema` — Optional. Ignored — login validates credentials, not props.
1166
1318
 
1167
- **Returns:** A request handler that responds with `{ statusCode: 200, body: { props } }` on success, or `{ statusCode: 206, body: { twoFactorRequired: true } }` when 2FA is needed.
1319
+ **Returns:** A request handler that responds with `{ statusCode: 200, body: { props, accessToken, user } }` on success, or `{ statusCode: 206, body: { twoFactorRequired: true } }` when 2FA is needed.
1168
1320
 
1169
1321
  ##### `handlers.LogInOAuthRequest`
1170
1322
 
@@ -1189,8 +1341,12 @@ Logs in or creates a user via OAuth. Verifies the authorization code with the bo
1189
1341
  provider (`get('oauth', serverName)`), then either finds an existing user by oauthServer+oauthId
1190
1342
  or creates a new one with a unique username. Sets JWT authorization and creates a session device.
1191
1343
 
1344
+ `schema` is optional and defaults to this package's `propsSchema`; supply one only when the
1345
+ app constrains or extends user props. It must expose `safeParse` — a stub fails the OAuth
1346
+ account-creation request with 400 `resource.error.unknownError`.
1347
+
1192
1348
  ```typescript
1193
- function logInOAuth({ name, tableName, schema }: types.Resource<unknown>): (
1349
+ function logInOAuth({ name, tableName, schema = propsSchema }: types.HandlerResource): (
1194
1350
  req: LogInOAuthRequest,
1195
1351
  res: MoleculeResponse,
1196
1352
  ) => Promise<
@@ -1214,10 +1370,10 @@ function logInOAuth({ name, tableName, schema }: types.Resource<unknown>): (
1214
1370
  >
1215
1371
  ```
1216
1372
 
1217
- - `resource` — The user resource configuration (name, tableName, schema).
1218
- - `resource.name` — The resource name.
1373
+ - `resource` — The user resource configuration: `{ name, tableName, schema? }`.
1374
+ - `resource.name` — The resource name used in error messages.
1219
1375
  - `resource.tableName` — The database table name for users.
1220
- - `resource.schema` — The validation schema for user properties.
1376
+ - `resource.schema` — Optional Zod schema validated when a new OAuth account is created. Defaults to `propsSchema`.
1221
1377
 
1222
1378
  **Returns:** A request handler that responds with `{ statusCode: 200, body: { props } }` on success.
1223
1379
 
@@ -1331,7 +1487,7 @@ function handlePaymentNotification({
1331
1487
  name,
1332
1488
  tableName,
1333
1489
  schema: _schema,
1334
- }: types.Resource<unknown>): (
1490
+ }: types.HandlerResource): (
1335
1491
  req: MoleculeRequest,
1336
1492
  ) => Promise<{ statusCode: number; body: string } | { statusCode: number; body: { error: string } }>
1337
1493
  ```
@@ -1339,7 +1495,7 @@ function handlePaymentNotification({
1339
1495
  - `resource` — The user resource configuration (name, tableName, schema).
1340
1496
  - `resource.name` — The resource name.
1341
1497
  - `resource.tableName` — The database table name for users.
1342
- - `resource.schema` — The validation schema for user properties.
1498
+ - `resource.schema` — Optional. Ignored — notifications validate with `updatePlanPropsSchema`.
1343
1499
 
1344
1500
  **Returns:** A request handler for payment provider notifications.
1345
1501
 
@@ -1356,7 +1512,7 @@ On successful verification, updates the user's plan (planKey, planExpiresAt, pla
1356
1512
  and stores the payment record via the bonded PaymentRecordService.
1357
1513
 
1358
1514
  ```typescript
1359
- function verifyPayment({ name, tableName, schema: _schema }: types.Resource<unknown>): (
1515
+ function verifyPayment({ name, tableName, schema: _schema }: types.HandlerResource): (
1360
1516
  req: MoleculeRequest,
1361
1517
  ) => Promise<
1362
1518
  | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
@@ -1378,7 +1534,7 @@ function verifyPayment({ name, tableName, schema: _schema }: types.Resource<unkn
1378
1534
  - `resource` — The user resource configuration (name, tableName, schema).
1379
1535
  - `resource.name` — The resource name.
1380
1536
  - `resource.tableName` — The database table name for users.
1381
- - `resource.schema` — The validation schema for user properties.
1537
+ - `resource.schema` — Optional. Ignored — plan fields are written directly after provider verification.
1382
1538
 
1383
1539
  **Returns:** A request handler for payment verification.
1384
1540
 
@@ -1393,7 +1549,7 @@ function read({
1393
1549
  name: _name,
1394
1550
  tableName,
1395
1551
  schema: _schema,
1396
- }: types.Resource<unknown>): (
1552
+ }: types.HandlerResource): (
1397
1553
  req: MoleculeRequest,
1398
1554
  res: MoleculeResponse,
1399
1555
  ) => Promise<{ statusCode: number; body: Record<string, unknown> }>
@@ -1402,7 +1558,7 @@ function read({
1402
1558
  - `resource` — The user resource configuration (name, tableName, schema).
1403
1559
  - `resource.name` — The resource name.
1404
1560
  - `resource.tableName` — The database table name for users.
1405
- - `resource.schema` — The validation schema for user properties.
1561
+ - `resource.schema` — Optional. Ignored — reads do not validate props.
1406
1562
 
1407
1563
  **Returns:** A request handler that responds with `{ statusCode: 200, body: { props, plan?, twoFactorEnabled? } }`.
1408
1564
 
@@ -1420,19 +1576,26 @@ so the client can re-establish `authenticated` state WITHOUT the token ever
1420
1576
  being exposed to JavaScript. Always self, so it mirrors `read`'s self branch
1421
1577
  (plan + two-factor status).
1422
1578
 
1579
+ **Token-only clients get the token back as `accessToken`.** When the request
1580
+ authenticated with an `Authorization` header (any accepted scheme — `Bearer` or
1581
+ `Token`), the middleware records that raw JWT and this response echoes it, so a
1582
+ RealWorld-style client can restore `{ user, token }` from `GET /user` the same way
1583
+ login and registration return it. A session resolved from the httpOnly cookie
1584
+ NEVER gets this field: exposing that token to JavaScript would defeat the cookie.
1585
+
1423
1586
  ```typescript
1424
1587
  function readSelf({
1425
1588
  tableName,
1426
- }: types.Resource<unknown>): (
1589
+ }: types.HandlerResource): (
1427
1590
  _req: MoleculeRequest,
1428
1591
  res: MoleculeResponse,
1429
1592
  ) => Promise<{ statusCode: number; body: Record<string, unknown> }>
1430
1593
  ```
1431
1594
 
1432
- - `resource` — The user resource configuration (name, tableName, schema).
1595
+ - `resource` — The user resource configuration: `{ name, tableName, schema? }` (`name` and `schema` are optional here).
1433
1596
  - `resource.tableName` — The database table name for users.
1434
1597
 
1435
- **Returns:** A request handler responding `{ statusCode: 200, body: { props, plan?, twoFactorEnabled? } }`, or 401 when unauthenticated.
1598
+ **Returns:** A request handler responding `{ statusCode: 200, body: { props, plan?, twoFactorEnabled?, accessToken? } }`, or 401 when unauthenticated.
1436
1599
 
1437
1600
  ##### `handlers.RESET_TOKEN_TTL_MS`
1438
1601
 
@@ -1482,7 +1645,7 @@ function resetPassword({
1482
1645
  name: _name,
1483
1646
  tableName,
1484
1647
  schema: _schema,
1485
- }: types.Resource<unknown>): (
1648
+ }: types.HandlerResource): (
1486
1649
  req: ResetPasswordRequest,
1487
1650
  ) => Promise<
1488
1651
  | { statusCode: number; body: { error: string; errorKey: string; success?: undefined } }
@@ -1492,6 +1655,7 @@ function resetPassword({
1492
1655
 
1493
1656
  - `resource` — The user resource configuration (name, tableName, schema).
1494
1657
  - `resource.tableName` — The database table name for users.
1658
+ - `resource.schema` — Optional. Ignored — the reset flow writes the password hash directly.
1495
1659
 
1496
1660
  **Returns:** A request handler that responds with `{ statusCode: 200, body: { success: true } }` on success.
1497
1661
 
@@ -1500,11 +1664,15 @@ function resetPassword({
1500
1664
  Updates a user's profile fields (username, name, email). Validates username format
1501
1665
  (alphanumeric, max 255 chars), email format, and uniqueness of both fields against
1502
1666
  other users before delegating to the resource update utility.
1667
+ `schema` is optional and NOT used here: this handler validates the partial update with the
1668
+ package's own `extendedUpdatePropsSchema` (username, name, email, avatar, bio, plus
1669
+ `oauthData`), so callers need not invent one. Statuses: 200 updated props; 400 for an invalid
1670
+ username/email, an oversized avatar/bio, a malformed `oauthData`, a missing `currentPassword`,
1671
+ or no updatable fields; 403 `user.error.usernameUnavailable` / `user.error.emailAlreadyRegistered`
1672
+ / `user.error.currentPasswordIncorrect`; 500 `user.error.failedToUpdateUser`.
1503
1673
 
1504
1674
  ```typescript
1505
- function update({ name, tableName, schema: _schema }: types.Resource<unknown>): (
1506
- req: MoleculeRequest,
1507
- ) => Promise<
1675
+ function update({ name, tableName }: types.HandlerResource): (req: MoleculeRequest) => Promise<
1508
1676
  | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
1509
1677
  | {
1510
1678
  statusCode: number
@@ -1517,10 +1685,10 @@ function update({ name, tableName, schema: _schema }: types.Resource<unknown>):
1517
1685
  >
1518
1686
  ```
1519
1687
 
1520
- - `resource` — The user resource configuration (name, tableName, schema).
1521
- - `resource.name` — The resource name.
1688
+ - `resource` — The user resource configuration: `{ name, tableName, schema? }`.
1689
+ - `resource.name` — The resource name used in error messages.
1522
1690
  - `resource.tableName` — The database table name for users.
1523
- - `resource.schema` — The validation schema for user properties.
1691
+ - `resource.schema` — Optional. Ignored — updates validate with this package's update schema.
1524
1692
 
1525
1693
  **Returns:** A request handler that responds with the updated user props on success.
1526
1694
 
@@ -1543,13 +1711,23 @@ Updates a user's password. If the user already has a password hash, the current
1543
1711
  must be provided and verified first. The new password is hashed via `@molecule/api-password`
1544
1712
  and stored in the secrets table.
1545
1713
 
1714
+ **Every OTHER session is revoked; the caller's own is kept.** The device rows of all other
1715
+ devices are deleted, so a stolen token on another device dies — but the device this request
1716
+ arrived on stays, and the token that made the request (the `Authorization` header the client
1717
+ is holding) keeps working. A RealWorld-style suite changes the password and then keeps using
1718
+ the same token for the next request; revoking the caller too is what answered its second
1719
+ `PUT /user` with 401 (xr-flash-m167, ~2 min lost). Do not fold a per-user secret into the
1720
+ JWT: the device row is the revocation lever. A caller with no session (a handler invoked
1721
+ outside a request) falls back to revoking every device.
1722
+
1546
1723
  ```typescript
1547
1724
  function updatePassword({
1548
1725
  name: _name,
1549
1726
  tableName,
1550
1727
  schema: _schema,
1551
- }: types.Resource<unknown>): (
1728
+ }: types.HandlerResource): (
1552
1729
  req: UpdatePasswordRequest,
1730
+ res?: MoleculeResponse,
1553
1731
  ) => Promise<
1554
1732
  | { statusCode: number; body: { error: string; errorKey: string; success?: undefined } }
1555
1733
  | { statusCode: number; body: { success: boolean; error?: undefined; errorKey?: undefined } }
@@ -1559,7 +1737,7 @@ function updatePassword({
1559
1737
  - `resource` — The user resource configuration (name, tableName, schema).
1560
1738
  - `resource.name` — The resource name.
1561
1739
  - `resource.tableName` — The database table name for users.
1562
- - `resource.schema` — The validation schema for user properties.
1740
+ - `resource.schema` — Optional. Ignored — this handler writes the password hash directly.
1563
1741
 
1564
1742
  **Returns:** A request handler that responds with `{ statusCode: 200, body: { success: true } }` on success.
1565
1743
 
@@ -1592,7 +1770,7 @@ cross-platform subscription cancellation when switching providers. Returns a che
1592
1770
  and free plan downgrades.
1593
1771
 
1594
1772
  ```typescript
1595
- function updatePlan({ name, tableName, schema: _schema }: types.Resource<unknown>): (
1773
+ function updatePlan({ name, tableName, schema: _schema }: types.HandlerResource): (
1596
1774
  req: UpdatePlanRequest,
1597
1775
  ) => Promise<
1598
1776
  | { statusCode: number; body: { error: string; errorKey: string; props?: undefined } }
@@ -1611,7 +1789,7 @@ function updatePlan({ name, tableName, schema: _schema }: types.Resource<unknown
1611
1789
  - `resource` — The user resource configuration (name, tableName, schema).
1612
1790
  - `resource.name` — The resource name.
1613
1791
  - `resource.tableName` — The database table name for users.
1614
- - `resource.schema` — The validation schema for user properties.
1792
+ - `resource.schema` — Optional. Ignored — plan updates validate with `updatePlanPropsSchema`.
1615
1793
 
1616
1794
  **Returns:** A request handler for plan updates.
1617
1795
 
@@ -1637,7 +1815,7 @@ Handles two-factor authentication lifecycle via `@molecule/api-two-factor`:
1637
1815
  - `disable`: Verifies a TOTP token against the active secret, then deactivates 2FA.
1638
1816
 
1639
1817
  ```typescript
1640
- function verifyTwoFactor({ name: _name, tableName, schema: _schema }: types.Resource<unknown>): (
1818
+ function verifyTwoFactor({ name: _name, tableName, schema: _schema }: types.HandlerResource): (
1641
1819
  req: VerifyTwoFactorRequest,
1642
1820
  ) => Promise<
1643
1821
  | { statusCode: number; body: { error: string; errorKey: string; twoFactorEnabled?: undefined } }
@@ -1662,7 +1840,7 @@ function verifyTwoFactor({ name: _name, tableName, schema: _schema }: types.Reso
1662
1840
  - `resource` — The user resource configuration (name, tableName, schema).
1663
1841
  - `resource.name` — The resource name.
1664
1842
  - `resource.tableName` — The database table name for users.
1665
- - `resource.schema` — The validation schema for user properties.
1843
+ - `resource.schema` — Optional. Ignored — 2FA state is written to the secrets table directly.
1666
1844
 
1667
1845
  **Returns:** A request handler for two-factor authentication operations.
1668
1846
 
@@ -1767,6 +1945,42 @@ An object describing the `user` resource.
1767
1945
  type Resource<T = unknown> = resourceTypes.Resource<T>
1768
1946
  ```
1769
1947
 
1948
+ ##### `types.HandlerResource`
1949
+
1950
+ Configuration accepted by every user handler factory (`handlers.create`,
1951
+ `handlers.logIn`, `handlers.update`, …).
1952
+
1953
+ `name` and `tableName` are the caller's to supply, because an app may mount the
1954
+ user resource on its own table. `schema` is OPTIONAL — no factory requires you
1955
+ to invent one:
1956
+
1957
+ - `handlers.create` and `handlers.logInOAuth` validate the props they write and
1958
+ default to this package's {@link propsSchema} when `schema` is omitted.
1959
+ - `handlers.update` validates with the package's `updatePropsSchema` and ignores
1960
+ a supplied `schema`.
1961
+ - The remaining handlers read/write rows directly and never look at `schema`.
1962
+
1963
+ Omission is NOT "no validation": the handlers that validate use
1964
+ {@link propsSchema}. Pass `createResource({ oauthServers, planKeys })` (or the
1965
+ `resource` export) when the app constrains `oauthServer` / `planKey`, and pass
1966
+ your own extended Zod object only when you add fields.
1967
+
1968
+ ```typescript
1969
+ interface HandlerResource {
1970
+ /** The resource name used in error messages (e.g. `'User'`). */
1971
+ name: string
1972
+ /** The database table name for users. */
1973
+ tableName: string
1974
+ /**
1975
+ * Optional Zod schema validated by `handlers.create` / `handlers.logInOAuth`.
1976
+ * Defaults to {@link propsSchema}. Must expose `safeParse`; a stub object is not
1977
+ * a schema and the first request answers 400 `resource.error.unknownError` with
1978
+ * `TypeError: schema.safeParse is not a function`.
1979
+ */
1980
+ schema?: unknown
1981
+ }
1982
+ ```
1983
+
1770
1984
  #### `utilities`
1771
1985
 
1772
1986
  Re-exported as a namespace — reach every member below through it (e.g. `utilities.<name>`).
@@ -2062,6 +2276,26 @@ check for a SECOND one: a request can pass several mounts (`api/src/server.ts`'s
2062
2276
  passes sets the policy both halves read, and a laxer mount later in the chain cannot
2063
2277
  re-admit the cookie. If the app mounts two, mount it once instead.
2064
2278
 
2279
+ **The RealWorld token recipe (detail).** The scheme is configuration, not a second auth
2280
+ layer: `AUTH_SCHEME=Token` in the API's env, or `verifyMiddleware({ scheme: 'Token',
2281
+ allowCookieSession: false })` at the mount, makes every covered route accept
2282
+ `Authorization: Token <jwt>` (`Bearer` stays accepted too) and labels the sign-in response
2283
+ header with that scheme. The token is already in the body — `handlers.logIn` and
2284
+ `handlers.create` return `{ props, accessToken, user }`, and `GET /users/me` adds
2285
+ `accessToken` when the request authenticated with the header (never for a cookie-resolved
2286
+ session: that token must stay unreadable to JavaScript).
2287
+
2288
+ ```typescript
2289
+ // Token-only API that speaks RealWorld's scheme.
2290
+ router.use(verifyMiddleware({ scheme: 'Token', allowCookieSession: false }))
2291
+ // POST /users and POST /users/log-in answer { props, accessToken, user };
2292
+ // clients send `Authorization: Token <accessToken>` from then on.
2293
+ ```
2294
+
2295
+ The CLIENT labels its header the same way: `authScheme: 'Token'` is an option of the HTTP
2296
+ client's CONSTRUCTOR (`createFetchClient({ baseURL, authScheme: 'Token' })`, or the axios
2297
+ provider's `createAxiosClient`), never a property of `getClient()`'s result.
2298
+
2065
2299
  **Revoking a session yourself:** the middleware caches "this device exists" for 10 s per
2066
2300
  process, so a hand-written logout that deletes the `devices` row keeps authorizing that
2067
2301
  token until the cache expires — a check right after logout still answers 200. Call