express-file-cluster 0.10.0 → 0.10.2

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 (186) hide show
  1. package/dist/auth/index.cjs +7 -6
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +5 -5
  6. package/dist/{chunk-R52CUEGT.js → chunk-3SWI46YK.js} +2 -2
  7. package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
  8. package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
  9. package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
  10. package/dist/chunk-74BSJXWD.cjs +220 -0
  11. package/dist/chunk-74BSJXWD.cjs.map +1 -0
  12. package/dist/{chunk-7KO4DJRJ.cjs → chunk-7BC3AN7R.cjs} +14 -14
  13. package/dist/{chunk-7KO4DJRJ.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
  14. package/dist/chunk-AGOYTFRO.cjs +42 -0
  15. package/dist/chunk-AGOYTFRO.cjs.map +1 -0
  16. package/dist/{chunk-RAB44UGX.js → chunk-B6MB6HEG.js} +1 -1
  17. package/dist/{chunk-PGJQK36V.js → chunk-BG4A7Z32.js} +7 -5
  18. package/dist/{chunk-PGJQK36V.js.map → chunk-BG4A7Z32.js.map} +1 -1
  19. package/dist/{chunk-ATVD2HGC.js → chunk-C2FOZ7ME.js} +4 -4
  20. package/dist/chunk-CGY7JU4Y.cjs +8 -0
  21. package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
  22. package/dist/{chunk-EGSSZUVO.js → chunk-DN4TCGYB.js} +38 -11
  23. package/dist/chunk-DN4TCGYB.js.map +1 -0
  24. package/dist/{chunk-GBI77W5T.cjs → chunk-H2PVWCWC.cjs} +1 -1
  25. package/dist/{chunk-GBI77W5T.cjs.map → chunk-H2PVWCWC.cjs.map} +1 -1
  26. package/dist/{chunk-NKLOE4AK.cjs → chunk-IUZ6A7PB.cjs} +20 -53
  27. package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
  28. package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
  29. package/dist/chunk-JP36TLL4.cjs.map +1 -0
  30. package/dist/chunk-KLWL7XSC.js +220 -0
  31. package/dist/chunk-KLWL7XSC.js.map +1 -0
  32. package/dist/{chunk-4DOHQU6I.cjs → chunk-M53GODCX.cjs} +39 -12
  33. package/dist/chunk-M53GODCX.cjs.map +1 -0
  34. package/dist/{chunk-R4XO4SVM.js → chunk-MUVO7MGS.js} +4 -4
  35. package/dist/{chunk-HBCY7ILD.cjs → chunk-R2K7AFIB.cjs} +97 -95
  36. package/dist/chunk-R2K7AFIB.cjs.map +1 -0
  37. package/dist/{chunk-QDEDOHP7.js → chunk-RETV3GKE.js} +9 -42
  38. package/dist/chunk-RETV3GKE.js.map +1 -0
  39. package/dist/{chunk-WBLUGOAG.cjs → chunk-RPL2IFWK.cjs} +8 -5
  40. package/dist/chunk-RPL2IFWK.cjs.map +1 -0
  41. package/dist/{chunk-YK4ZM3CA.cjs → chunk-TBIVIR6L.cjs} +15 -15
  42. package/dist/{chunk-YK4ZM3CA.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
  43. package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
  44. package/dist/chunk-V73R76I4.js.map +1 -0
  45. package/dist/chunk-XPY5TQDK.js +42 -0
  46. package/dist/chunk-XPY5TQDK.js.map +1 -0
  47. package/dist/{chunk-KFVFP2Q7.cjs → chunk-Y4NKIXUL.cjs} +70 -55
  48. package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
  49. package/dist/{chunk-7KC2H76D.js → chunk-Y75V5FCU.js} +62 -47
  50. package/dist/chunk-Y75V5FCU.js.map +1 -0
  51. package/dist/cli/db-runner.cjs +81 -42
  52. package/dist/cli/db-runner.cjs.map +1 -1
  53. package/dist/cli/db-runner.js +54 -16
  54. package/dist/cli/db-runner.js.map +1 -1
  55. package/dist/cli/index.cjs +23 -25
  56. package/dist/cli/index.cjs.map +1 -1
  57. package/dist/cli/index.js +12 -17
  58. package/dist/cli/index.js.map +1 -1
  59. package/dist/docs/api-reference/auth.md +23 -0
  60. package/dist/docs/api-reference/compose.md +1 -1
  61. package/dist/docs/api-reference/db.md +8 -0
  62. package/dist/docs/api-reference/ignite.md +4 -1
  63. package/dist/docs/api-reference/testing.md +26 -0
  64. package/dist/docs/cli/add.md +2 -2
  65. package/dist/docs/core-concepts/file-based-routing.md +2 -0
  66. package/dist/docs/core-concepts/middleware.md +2 -2
  67. package/dist/docs/getting-started/index.md +4 -0
  68. package/dist/docs/guides/authentication.md +33 -0
  69. package/dist/docs/guides/caching.md +2 -0
  70. package/dist/docs/guides/database.md +15 -0
  71. package/dist/docs/guides/environment-variables.md +6 -0
  72. package/dist/docs/guides/generated-portals.md +3 -1
  73. package/dist/docs/guides/logging.md +17 -0
  74. package/dist/docs/guides/migrations.md +4 -2
  75. package/dist/docs/guides/testing.md +31 -0
  76. package/dist/docs/index.md +2 -1
  77. package/dist/docs/skills/SKILL.md +5 -1
  78. package/dist/docs/skills/api-surface.md +20 -4
  79. package/dist/docs/skills/auth-internals.md +14 -1
  80. package/dist/docs/skills/pre-flight.md +6 -0
  81. package/dist/docs/skills/routing-rules.md +1 -1
  82. package/dist/docs/skills/what-not-to-invent.md +9 -1
  83. package/dist/docs/versioning.md +1 -1
  84. package/dist/index.cjs +75 -264
  85. package/dist/index.cjs.map +1 -1
  86. package/dist/index.d.cts +27 -3
  87. package/dist/index.d.ts +27 -3
  88. package/dist/index.js +28 -218
  89. package/dist/index.js.map +1 -1
  90. package/dist/pgboss-backend-4X2YT4RB.js +14 -0
  91. package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
  92. package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
  93. package/dist/registry/index.json +27 -3
  94. package/dist/registry/js-mongo/account-security.json +1 -1
  95. package/dist/registry/js-mongo/admin-users.json +1 -1
  96. package/dist/registry/js-mongo/auth.json +1 -1
  97. package/dist/registry/js-mongo/auth@apple.json +1 -1
  98. package/dist/registry/js-mongo/auth@google.json +1 -1
  99. package/dist/registry/js-mongo/forgot-password.json +1 -1
  100. package/dist/registry/js-mongo/user-profile.json +1 -1
  101. package/dist/registry/js-mongo-collection/account-security.json +1 -1
  102. package/dist/registry/js-mongo-collection/admin-users.json +1 -1
  103. package/dist/registry/js-mongo-collection/auth.json +1 -1
  104. package/dist/registry/js-mongo-collection/auth@apple.json +1 -1
  105. package/dist/registry/js-mongo-collection/auth@google.json +1 -1
  106. package/dist/registry/js-mongo-collection/forgot-password.json +1 -1
  107. package/dist/registry/js-mongo-collection/user-profile.json +1 -1
  108. package/dist/registry/js-pg-model/account-security.json +1 -1
  109. package/dist/registry/js-pg-model/admin-users.json +1 -1
  110. package/dist/registry/js-pg-model/auth.json +1 -1
  111. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  112. package/dist/registry/js-pg-model/auth@google.json +1 -1
  113. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  114. package/dist/registry/js-pg-model/user-profile.json +1 -1
  115. package/dist/registry/js-pg-table/account-security.json +1 -1
  116. package/dist/registry/js-pg-table/admin-users.json +1 -1
  117. package/dist/registry/js-pg-table/auth.json +1 -1
  118. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  119. package/dist/registry/js-pg-table/auth@google.json +1 -1
  120. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  121. package/dist/registry/js-pg-table/user-profile.json +1 -1
  122. package/dist/registry/ts-mongo/account-security.json +1 -1
  123. package/dist/registry/ts-mongo/admin-users.json +1 -1
  124. package/dist/registry/ts-mongo/auth.json +1 -1
  125. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  126. package/dist/registry/ts-mongo/auth@google.json +1 -1
  127. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  128. package/dist/registry/ts-mongo/user-profile.json +1 -1
  129. package/dist/registry/ts-mongo-collection/account-security.json +1 -1
  130. package/dist/registry/ts-mongo-collection/admin-users.json +1 -1
  131. package/dist/registry/ts-mongo-collection/auth.json +1 -1
  132. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -1
  133. package/dist/registry/ts-mongo-collection/auth@google.json +1 -1
  134. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -1
  135. package/dist/registry/ts-mongo-collection/user-profile.json +1 -1
  136. package/dist/registry/ts-pg-model/account-security.json +1 -1
  137. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  138. package/dist/registry/ts-pg-model/auth.json +1 -1
  139. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  140. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  141. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  142. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  143. package/dist/registry/ts-pg-table/account-security.json +1 -1
  144. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  145. package/dist/registry/ts-pg-table/auth.json +1 -1
  146. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  147. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  148. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  149. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  150. package/dist/tasks/index.cjs +3 -2
  151. package/dist/tasks/index.cjs.map +1 -1
  152. package/dist/tasks/index.d.cts +1 -1
  153. package/dist/tasks/index.d.ts +1 -1
  154. package/dist/tasks/index.js +1 -1
  155. package/dist/testing-cjs.cjs +5 -0
  156. package/dist/testing.cjs +59 -0
  157. package/dist/testing.cjs.map +1 -0
  158. package/dist/testing.d.cts +27 -0
  159. package/dist/testing.d.ts +27 -0
  160. package/dist/testing.js +58 -0
  161. package/dist/testing.js.map +1 -0
  162. package/dist/thread-runner.cjs +4 -3
  163. package/dist/thread-runner.cjs.map +1 -1
  164. package/dist/thread-runner.js +2 -2
  165. package/dist/{types-Bnxvj3l0.d.ts → types-CPMFTVXm.d.cts} +8 -0
  166. package/dist/{types-Bnxvj3l0.d.cts → types-CPMFTVXm.d.ts} +8 -0
  167. package/package.json +6 -1
  168. package/dist/chunk-4DOHQU6I.cjs.map +0 -1
  169. package/dist/chunk-73XJUT2S.js.map +0 -1
  170. package/dist/chunk-7KC2H76D.js.map +0 -1
  171. package/dist/chunk-DUADUR6R.cjs.map +0 -1
  172. package/dist/chunk-EGSSZUVO.js.map +0 -1
  173. package/dist/chunk-HBCY7ILD.cjs.map +0 -1
  174. package/dist/chunk-KFVFP2Q7.cjs.map +0 -1
  175. package/dist/chunk-NKLOE4AK.cjs.map +0 -1
  176. package/dist/chunk-QDEDOHP7.js.map +0 -1
  177. package/dist/chunk-WBLUGOAG.cjs.map +0 -1
  178. package/dist/pgboss-backend-FW42SBSM.js +0 -14
  179. package/dist/pgboss-backend-RVHUBJTU.cjs +0 -14
  180. package/dist/pgboss-backend-RVHUBJTU.cjs.map +0 -1
  181. /package/dist/{chunk-R52CUEGT.js.map → chunk-3SWI46YK.js.map} +0 -0
  182. /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
  183. /package/dist/{chunk-RAB44UGX.js.map → chunk-B6MB6HEG.js.map} +0 -0
  184. /package/dist/{chunk-ATVD2HGC.js.map → chunk-C2FOZ7ME.js.map} +0 -0
  185. /package/dist/{chunk-R4XO4SVM.js.map → chunk-MUVO7MGS.js.map} +0 -0
  186. /package/dist/{pgboss-backend-FW42SBSM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
@@ -267,3 +267,26 @@ Accepts any value the [`jose`](https://github.com/panva/jose) library supports:
267
267
  ## Algorithm
268
268
 
269
269
  Tokens are signed with **HS256** (HMAC-SHA256). The secret is UTF-8 encoded before signing. Asymmetric algorithms (RS256, ES256) are not currently supported.
270
+
271
+ ## Generated account-security routes
272
+
273
+ These are app templates, not exports from `/auth`. `POST /auth/change-password` verifies the authenticated account's old password, hashes the replacement, clears stored refresh credentials, and uses `revokeAllSessions` (cache required). Its 200 response is `{ message: 'Password changed successfully' }`; invalid input returns 400, invalid credentials 401, and suspended accounts 403. Revocation failures propagate. Existing access tokens, including the caller's, are revoked.
274
+
275
+ Generated 2FA routes (app code, not additional core exports):
276
+
277
+ | Method/path | Input | Result |
278
+ |---|---|---|
279
+ | `GET /auth/2fa/setup` | authenticated | `{ enabled, method, methods }` |
280
+ | `POST /auth/2fa/setup` | authenticated; `{ password, method }` | TOTP secret/`otpauthUrl` (200), or email `codeSent` (202) |
281
+ | `POST /auth/2fa/setup` | authenticated; `{ password, method, code }` | confirms enrollment; revokes sessions (200) |
282
+ | `POST /auth/login`, `POST /auth/2fa/verify` | `{ email, password, code? }` | no tokens until the enrolled factor passes; missing/invalid code returns 401 with `twoFactorRequired` and `method`; a password-verified email request without code sends one |
283
+ | `POST /auth/2fa/disable` | authenticated; `{ password, code? }` | email without code sends a disable code (202); valid password/code disables and revokes sessions (200) |
284
+
285
+ `TWO_FACTOR_METHOD=totp|email|both` limits enrollment choices. Each account has one method. TOTP is six-digit SHA-1 with 30-second steps (±1 step); email codes last five minutes. Accepted codes cannot be reused. Enrollment/disable require the current password. See [the full flow and upgrade steps](../guides/authentication.md#two-factor-authentication-totp-or-email-otp).
286
+
287
+ Device-session `/auth/sessions` (GET) and `/auth/sessions/:id` (DELETE) remain authenticated 501 extension points.
288
+
289
+
290
+ Generated User/Admin logout requires authentication, compare-and-sets the account's stored refresh token to empty (including bearer logout with no refresh cookie/body), then revokes the current access token and clears cookies. Login persists refresh credentials only while the password hash still matches its verified snapshot. Generated login/refresh tokens carry `efc_auth_at`, captured before credential reads; revocation rejects a token whose authentication started at or before the cutoff, even if it was signed afterwards. Custom token issuers may include this numeric epoch-millisecond claim for the same protection; it can only restrict access, never override a later server-issued time. Existing generated apps must update their owned auth routes as well as the framework to receive these fixes.
291
+
292
+ Password reset atomically consumes the matching, still-unexpired reset token while replacing the password and clearing stored refresh credentials and pending 2FA challenges. Concurrent use has one winner; expiry is rechecked in the database after hashing. Active 2FA enrollment remains enabled. Password changes also invalidate outstanding reset links. Custom auth-entity logout propagates revocation-store failures instead of returning a false success. Existing apps must update their owned reset-password, change-password, two-factor helper and custom logout files.
@@ -41,7 +41,7 @@ export const POST = compose(
41
41
  ## Behaviour
42
42
 
43
43
  - Handlers are called in the order they are passed.
44
- - Each handler receives the real `next` function of its predecessor; calling `next()` advances to the next handler in the chain.
44
+ - Calling `next()` (or `next(null)`) advances to the next handler in the chain. Calling `next(err)` stops the chain and forwards the error to Express; `next('route')` and `next('router')` are forwarded to Express as well.
45
45
  - If the last handler calls `next()`, control passes to the surrounding Express middleware chain (equivalent to the route calling `next()`).
46
46
  - If any handler throws synchronously or returns a rejected promise, the error is forwarded to `next(err)` and bubbles up to the global error handler.
47
47
 
@@ -350,3 +350,11 @@ It throws if accessed before Pre-Flight completes (e.g. at module load time) —
350
350
  ### `getDbClient()` / `setDbClient()`
351
351
 
352
352
  Read or replace the client behind `db` — mainly for tests that bypass `ignite()`.
353
+
354
+ ## PostgreSQL statement preparation
355
+
356
+ `ignite({ databasePool: { preparedStatements: true | false | { max?: number } } })` controls automatic naming of Drizzle model queries, including transaction queries. Default: `true`, with 100 names per physical connection. `max` must be a nonnegative safe integer; zero disables. Reused SQL shapes share names across values; excess new shapes use unnamed execution. The native `db` Pool and explicitly named driver queries retain their behavior. EFC schema sync/drop invalidates reusable shapes without exceeding the connection's lifetime name budget. Reconnect after external DDL; disable for incompatible poolers. See [database guide](../guides/database.md#postgresql-prepared-statements).
357
+
358
+ ## Query metrics
359
+
360
+ `getQueryMetrics(): QueryMetricsSnapshot` and `resetQueryMetrics(): void` are exported from the main package. Opt in using `logging.queries.metrics: true | { maxEntries?: number }` (default off; enabled default limit 1000; zero disables). A snapshot contains `enabled`, `since` (epoch ms), `dropped` (untracked completed-call observations), and detached `entries: ReadonlyArray<QueryMetric>`. Each metric has `model`, `op`, `calls`, `errors`, `statements`, `totalMs`, `minMs`, `maxMs`, `meanMs`, `slow`. Reset starts a new process-local window and leaves collection enabled. Values/SQL/error strings are never included. Nested calls' statement counts are inclusive. [Details](../guides/logging.md#query-metrics).
@@ -31,7 +31,7 @@ interface EFCConfig {
31
31
  // Database
32
32
  database?: 'mongodb' | 'postgresql';
33
33
  databaseUrl?: string;
34
- databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number };
34
+ databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number; preparedStatements?: boolean | { max?: number } };
35
35
 
36
36
  // Auth
37
37
  authStrategy?: 'http-only' | 'bearer'; // 'localStorage' = old name for 'bearer'
@@ -171,6 +171,7 @@ databasePool: { max: 5, idleTimeoutMs: 30_000, connectionTimeoutMs: 5_000 },
171
171
  | Option | PostgreSQL (`pg` Pool) | MongoDB (mongoose) |
172
172
  |---|---|---|
173
173
  | `max` | `max` — default 10 | `maxPoolSize` — default 100 |
174
+ | `preparedStatements` | `true` (default): up to 100 named statements per connection; `{ max: n }` changes the lifetime budget, `false` / `{ max: 0 }` disables | ignored |
174
175
  | `idleTimeoutMs` | `idleTimeoutMillis` — default 10000 | `maxIdleTimeMS` — default: never |
175
176
  | `connectionTimeoutMs` | `connectionTimeoutMillis` — default: no limit | `serverSelectionTimeoutMS` (default 30000) and `waitQueueTimeoutMS` (default: no limit) |
176
177
 
@@ -362,3 +363,5 @@ ignite({ port: 3000 })
362
363
  | `timeoutMs` | `number` | `10_000` | Force-exit after this many milliseconds if `server.close()` hasn't finished |
363
364
 
364
365
  On a worker, the signal closes the HTTP server (in-flight requests finish), drains running task jobs, then exits. On the cluster primary it relays `SIGTERM` to every worker — so `docker stop` / Kubernetes, which signal only PID 1, still shut down gracefully — and force-exits after `timeoutMs + 2s` if a worker hangs. Repeated signals are ignored rather than killing a worker mid-drain.
366
+
367
+ `logging.queries.metrics: true | { maxEntries?: number }` enables bounded per-process query counters and latency summaries (default off; enabled default limit 1000). Read/reset through `getQueryMetrics` / `resetQueryMetrics` from the main package; see [query metrics](../guides/logging.md#query-metrics).
@@ -0,0 +1,26 @@
1
+ # `createTestApp(options)`
2
+
3
+ ```ts
4
+ import { createTestApp } from 'express-file-cluster/testing';
5
+ import type { TestAppOptions } from 'express-file-cluster/testing';
6
+ ```
7
+
8
+ Returns `Promise<express.Express>` with real file-based routes mounted, without starting a listener or booting services.
9
+
10
+ | Option | Default | Behavior |
11
+ |---|---|---|
12
+ | `apiDir: string` | required | Absolute path, or path resolved against the current working directory; rejects a nonexistent/non-directory path. |
13
+ | `basePath?: string` | `/v1/api` | Mount point for the API router. |
14
+ | `globalMiddlewares?: RequestHandler[]` | `[]` | Runs after body/cookie parsing and before file middleware/validation. |
15
+ | `auth?: { secret; strategy?; expiresIn?; cookieDomain? }` | unchanged | Configures process-wide auth; strategy defaults to `http-only`, expiry to `1h`. |
16
+ | `requestTimeout?: number` | disabled | Production request timeout in milliseconds; responds 408. |
17
+ | `trustProxy?` | Express default | Same value type as `EFCConfig.trustProxy`; supports client-IP tests behind a proxy. |
18
+ | `onError?: ErrorRequestHandler` | production error handler | Express error middleware mounted after the API. |
19
+
20
+ Shared behavior with production: JSON/form/cookie parsing, AsyncLocalStorage request context, request IDs, bigint JSON serialization, route scanning/order, file middleware, schema validation, method dispatch, and safe error responses. CORS, logging, the dashboard and service initialization are disabled/omitted. Auth/logging and imported modules retain process-wide state; see [test isolation](../guides/testing.md).
21
+
22
+ This helper's `apiDir` is **not** a new `ignite()` option. `createTestApp` is exported only from `/testing`; no `/db`, `/router` or `/middleware` subpaths are added.
23
+
24
+ The CommonJS `/testing` entry delegates to the ESM helper using native `import()`, so dynamically imported ESM routes share its authentication and request context. The Node/runner must support the route files' module format.
25
+
26
+ The ESM and CommonJS builds share process-wide auth configuration, request AsyncLocalStorage and cache state. CommonJS `requireAuth` global middleware therefore sees helper auth options, preserves `getCurrentUser()` across awaits into ESM routes, and observes the same revocations. Model/queue fixtures are still configured separately.
@@ -47,7 +47,7 @@ efc diff # compare installed features with the regi
47
47
  | `auth@apple` | Sign in with Apple: `GET /auth/apple` → Apple → `POST /auth/apple/callback` (+ `OAuthAccount`). Asks for Services ID, Team ID, Key ID and the `.p8` key | auth |
48
48
  | `user-profile` | `GET/PUT /user/profile` | auth |
49
49
  | `forgot-password` | `/auth/forgot-password`, `/auth/reset-password` | auth |
50
- | `account-security` | change password, 2FA, sessions, token refresh + `Session` model | auth |
50
+ | `account-security` | password changes, token refresh, TOTP/email OTP (asks allowed methods); device-session extension points return 501; `Session` model | auth |
51
51
  | `email-verification` | `/auth/verify-email`, resend | auth |
52
52
  | `account-settings` | avatar, settings, account, dashboard, activity | auth |
53
53
  | `notifications` | `Notification` model + `/user/notifications` | auth |
@@ -140,7 +140,7 @@ Wrong answers are asked again. A question is only asked for a variable the app d
140
140
 
141
141
  ```json
142
142
  {
143
- "registry": "0.10.0",
143
+ "registry": "0.10.2",
144
144
  "language": "typescript",
145
145
  "database": "postgresql",
146
146
  "modelApi": "defineTable",
@@ -23,6 +23,8 @@ EFC turns your directory tree into your route tree. The scanner walks `src/api/`
23
23
 
24
24
  **`[...spread]` → catch-all** — matches one or more remaining segments; `req.params.slug` is a **string array** (`/docs/a/b` → `['a', 'b']`, each segment URI-decoded). With double brackets it also matches zero segments (`[]`). A catch-all must be the last segment of the path — `[...slug]/edit.ts` is rejected at startup.
25
25
 
26
+ Catch-all paths are split into segments **before** each segment is URI-decoded once. `/docs/100%25/a%2Fb/a%252Fb` produces `['100%', 'a/b', 'a%2Fb']`; an encoded slash stays inside its original segment. Named parameters preceding the catch-all are also decoded once.
27
+
26
28
  **`index.ts` → parent path** — a file named `index.ts` (or `.js`) inside a directory maps to the directory's URL without a trailing `/index`.
27
29
 
28
30
  ---
@@ -74,7 +74,7 @@ export const POST = compose(
74
74
 
75
75
  ## How `compose` works
76
76
 
77
- `compose(...handlers)` in `packages/core/src/compose.ts` returns a single `RequestHandler` that chains the provided handlers in sequence. Each handler calls `next()` to advance to the next one. If any handler throws or rejects, the error is forwarded to Express's error chain via `next(err)`.
77
+ `compose(...handlers)` in `packages/core/src/compose.ts` returns a single `RequestHandler` that chains the provided handlers in sequence. Each handler calls `next()` to advance to the next one. Calling `next(err)` stops the composed chain and forwards the error; `next('route')` and `next('router')` retain their Express meanings. If any handler throws or rejects, the error is forwarded to Express's error chain via `next(err)`.
78
78
 
79
79
  ```ts
80
80
  export function compose(...handlers: RequestHandler[]): RequestHandler {
@@ -85,7 +85,7 @@ export function compose(...handlers: RequestHandler[]): RequestHandler {
85
85
  if (i >= handlers.length) { next(); return; }
86
86
  const handler = handlers[i];
87
87
  try {
88
- Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);
88
+ Promise.resolve(handler(req, res, (err) => err ? next(err) : dispatch(i + 1))).catch(next);
89
89
  } catch (err) {
90
90
  next(err);
91
91
  }
@@ -98,3 +98,7 @@ The server is live at `http://localhost:3000`. The scaffolder creates a `src/api
98
98
  - [Migrations & Seeds](../guides/migrations.md) — evolving the schema.
99
99
  - [Validation](../guides/validation.md) — `export const schema` with zod & co.
100
100
  - [CLI Reference](../cli/index.md) — all `efc` commands.
101
+
102
+ ### Choosing two-factor authentication
103
+
104
+ Select **Account security** in the init feature picker, then choose **Authenticator app (TOTP)**, **Email OTP**, or **Both — users choose**. Email/both automatically adds the SMTP email client and asks for mail settings. Each user or admin can enroll one allowed method. The generated `TWO_FACTOR_METHOD` setting controls the choices and `TWO_FACTOR_KEY` protects stored secrets; keep the key stable across deployments. See [enrollment, login and disable](../guides/authentication.md#two-factor-authentication-totp-or-email-otp).
@@ -282,3 +282,36 @@ future default doesn't lock anyone out. Apps scaffolded before 0.9.2 stored **bc
282
282
  `verifyPassword` deliberately rejects (EFC carries no bcrypt code or dependency): those users reset
283
283
  their password once — the reset route stores a scrypt hash. See the
284
284
  [auth API reference](../api-reference/auth.md#hashpassword--verifypassword--passwordneedsrehash).
285
+
286
+ ## Generated password changes and security extension points
287
+
288
+ `efc add account-security` adds a protected `POST /auth/change-password`. Send nonempty strings `oldPassword` and `newPassword`. The route verifies the current password for the authenticated User or Admin, stores a new `hashPassword()` hash, invalidates its stored refresh token, and revokes existing access tokens with `revokeAllSessions`. The current session is also revoked: log in again with the new password. The endpoint limits attempts to ten per account per fifteen minutes and needs the scaffolded cache.
289
+
290
+ Revocation errors propagate instead of reporting success. Because the database update precedes cache revocation, a cache failure can leave the new password persisted even though the request fails; restore cache access and log in again.
291
+
292
+ Device-session list/revoke routes remain authenticated 501 extension points. Two-factor authentication is implemented as generated app code, described below.
293
+
294
+ ## Two-factor authentication: TOTP or email OTP
295
+
296
+ When selecting **Account security** during `create-efc-app`, choose **Authenticator app (TOTP)**, **Email OTP**, or **Both — users choose**. Email-capable choices also add the email-client integration and ask for SMTP settings. `efc add account-security` asks the same method question; install `efc add email-client` as well when choosing email or both. `TWO_FACTOR_METHOD=totp|email|both` controls allowed methods; each User or Admin enrolls one allowed method. Changing the app setting does not silently downgrade enrolled accounts: an account using a method you disable cannot sign in until you restore it or migrate the account.
297
+
298
+ Keep the generated `TWO_FACTOR_KEY` (64 hex characters / 32 random bytes) in your secret store and identical across instances. It encrypts TOTP secrets with AES-256-GCM and authenticates stored email-code digests, independently of `JWT_SECRET`. Keep it when upgrading or rotating JWT keys. Replacing it without migrating/re-enrolling the accounts prevents verification of existing secrets.
299
+
300
+ 1. Authenticate, then `GET /auth/2fa/setup` to see `{ enabled, method, methods }`.
301
+ 2. Start enrollment with `POST /auth/2fa/setup`, body `{ password, method: 'totp' | 'email' }`. The current password is required. TOTP returns `{ secret, otpauthUrl, expiresIn: 600 }`: enter the secret in an authenticator or render the URI as a QR code in your UI. Email sends a six-digit code to the account's stored email and returns 202 `{ method: 'email', codeSent: true, expiresIn: 300 }`.
302
+ 3. Confirm with `POST /auth/2fa/setup`, body `{ password, method, code }`. The method must match the pending enrollment. Only a valid, unexpired code enables 2FA. Successful enrollment clears refresh credentials and revokes existing access tokens, including the current session.
303
+ 4. Sign in with `POST /auth/login` or `/auth/2fa/verify`, body `{ email, password, code }`. Both endpoints run the same credential checks and rate limit. Without a code, an enrolled account gets 401 `{ twoFactorRequired: true, method }` and no access/refresh token. For email accounts, this password-verified request sends the OTP; repeat with the received code. For TOTP, use the current authenticator code. Wrong passwords never send an email code.
304
+ 5. Disable with authenticated `POST /auth/2fa/disable`, body `{ password, code }`. Email users first send `{ password }` to request a purpose-specific disable code (202), then submit it. Disable requires the current password and a fresh code, erases secrets, clears refresh credentials, and revokes access tokens. To switch methods, disable the current one and enroll the other. Disable email 2FA before changing the email address through the profile route.
305
+
306
+ TOTP uses [RFC 6238](https://www.rfc-editor.org/rfc/rfc6238) SHA-1, six digits and 30-second intervals, accepting one interval of clock drift. Accepted time steps are atomically recorded so the same code cannot be reused, even across workers. Enrollment consumes its code too: wait for the next authenticator code before logging in. Email codes expire in five minutes, are purpose/account/address bound, and are consumed atomically; resending replaces the previous code. Only a keyed digest is stored. Pending TOTP secrets expire after ten minutes. Secret/code fields are stripped from generated record responses; enrollment responses use `Cache-Control: no-store`.
307
+
308
+ Login and verification share a ten-attempt per-account, fifteen-minute limit across both paths; management endpoints share a separate limit. These limits require the scaffolded cache and reject requests when it is unavailable. Use Redis across multiple app instances. SMTP settings and a working task backend are required for email delivery; queue failures invalidate the pending code and propagate instead of reporting success.
309
+
310
+ Refresh tokens are issued only after completing 2FA. Enabling/disabling clears older refresh tokens, and refresh rotation uses a database compare-and-set to reject replay. OAuth sign-in refuses accounts with 2FA enabled; use password plus verification code instead, so OAuth cannot bypass this app-level second factor. OAuth-only accounts must set a password before enrolling. Password reset does not disable 2FA. Recovery codes and automated lost-device recovery are not implemented; provide a separately verified support process before offering enrollment to end users.
311
+
312
+ Existing apps must update their auth-owned models, login/refresh/OAuth helpers and record sanitizers as well as the 2FA routes. Review `efc diff auth account-security`, preserve edited files, and run the normal model migration process if auto-sync is disabled. Set `TWO_FACTOR_KEY` and configure the mailer before enabling email OTP. Updating only the setup endpoint leaves other login paths unchanged.
313
+
314
+
315
+ Generated User/Admin logout requires authentication, compare-and-sets the account's stored refresh token to empty (including bearer logout with no refresh cookie/body), then revokes the current access token and clears cookies. Login persists refresh credentials only while the password hash still matches its verified snapshot. Generated login/refresh tokens carry `efc_auth_at`, captured before credential reads; revocation rejects a token whose authentication started at or before the cutoff, even if it was signed afterwards. Custom token issuers may include this numeric epoch-millisecond claim for the same protection; it can only restrict access, never override a later server-issued time. Existing generated apps must update their owned auth routes as well as the framework to receive these fixes.
316
+
317
+ Password reset atomically consumes the matching, still-unexpired reset token while replacing the password and clearing stored refresh credentials and pending 2FA challenges. Concurrent use has one winner; expiry is rechecked in the database after hashing. Active 2FA enrollment remains enabled. Password changes also invalidate outstanding reset links. Custom auth-entity logout propagates revocation-store failures instead of returning a false success. Existing apps must update their owned reset-password, change-password, two-factor helper and custom logout files.
@@ -153,3 +153,5 @@ cache: { backend: 'redis', url: process.env.REDIS_URL, onRevocationCheckError: '
153
153
  Either way the failure is logged (at most every 30 seconds), and calling `revokeSession` / `revokeAllSessions` during an outage **throws**, so a failed logout is never reported as a success. Plain `cache.get/set` calls are unaffected — they degrade to misses.
154
154
 
155
155
  `revokeToken(res)` still exists and only clears the cookie — prefer `revokeSession` when a cache is configured.
156
+
157
+ ESM and CommonJS imports share the configured backend, key prefix, pending cache fills and revocation failure policy within one process. A backend configured by one build is used by the other; closing it closes the shared backend. Use one application/cache configuration per process.
@@ -232,3 +232,18 @@ export default defineTask({ schedule: '0 * * * *' }, async () => {
232
232
  await Session.deleteMany({ expiresAt: { $lt: new Date() } });
233
233
  });
234
234
  ```
235
+
236
+ ## PostgreSQL prepared statements
237
+
238
+ EFC's PostgreSQL model queries use named prepared statements by default, through node-postgres. SQL shapes are reused across parameter values on each connection, including inside `transaction()`. Drizzle's encoders, row mode and result parsers are preserved; query logging still counts one execution as one statement. Native `db.query()` is unchanged.
239
+
240
+ ```ts
241
+ ignite({
242
+ databaseUrl: process.env.DATABASE_URL,
243
+ databasePool: { max: 5, preparedStatements: { max: 100 } },
244
+ });
245
+ ```
246
+
247
+ The default budget is 100 automatically named statements per physical connection. Existing shapes are reused; when the budget is full, new shapes run unnamed. There is no concurrent eviction/DEALLOCATE. Server statements remain bounded until the connection closes. EFC invalidates reusable shapes after its schema sync/drop changes a table, keeping the same lifetime budget. It does not automatically invalidate after DDL issued outside EFC: reconnect after external schema changes. Named statements explicitly supplied by an application are preserved and are outside this automatic budget. DDL, transaction control and multi-statement SQL are not automatically prepared.
248
+
249
+ Set `databasePool.preparedStatements: false` for transaction poolers that do not support named protocol statements. For PgBouncer, check its [prepared-statement configuration](https://www.pgbouncer.org/config.html#max_prepared_statements); do not assume every deployment supports it. MongoDB ignores this option. This feature avoids repeated parse work for reused SQL; it does not promise faster performance for every query.
@@ -104,3 +104,9 @@ SMTP_FROM=you@example.com
104
104
  In development (`efc start dev`), the CLI loads `.env` into `process.env` before your app runs, so `efc.config.ts`'s `process.env.X` reads see it. It re-reads `.env` fresh on every `tsx watch` restart — editing `.env` and saving a source file is enough to pick up the change, no need to stop and restart `efc start dev` itself. Variables already present in `process.env` (e.g. real OS-exported vars, CI-injected secrets) take precedence over `.env`.
105
105
 
106
106
  In production (`efc start prod`), `.env` is loaded if one exists in the working directory — handy on a plain VPS. Platforms (Docker, Kubernetes, Railway, Heroku) that inject secrets directly into `process.env` always win: the file only fills in variables that aren't already set.
107
+
108
+ ## Generated two-factor authentication
109
+
110
+ - `TWO_FACTOR_METHOD`: `totp` (default), `email`, or `both`. Init asks when Account security is selected; with both, each account chooses one method at enrollment. Disabling a method does not silently disable enrolled accounts.
111
+ - `TWO_FACTOR_KEY`: independent 32-byte encryption/HMAC key as 64 hex characters (`openssl rand -hex 32`). Init generates it for auth. Keep it stable and shared across instances; changing it requires migrating encrypted secrets or re-enrolling accounts. `ignite()` does not read it; generated `src/lib/two-factor` does.
112
+ - Email OTP needs the email-client's `SMTP_*` settings and a running task backend. Init automatically adds the email client for email/both; with `efc add account-security`, add `efc add email-client` too. Codes expire after five minutes.
@@ -17,13 +17,15 @@ The user and admin portals are a set of **registry items**: ready-made models an
17
17
 
18
18
  ---
19
19
 
20
+ The route inventory includes extension points as well as implemented handlers. In `account-security`, password changes, refresh rotation and 2FA (TOTP/email OTP) work. Init asks which methods the app allows; users enroll one of them. Device-session list/revoke still return **501 Not Implemented** until you connect a device-session store. See [the 2FA flow](./authentication.md#two-factor-authentication-totp-or-email-otp). Other portal templates can also contain TODOs and need application logic before use.
21
+
20
22
  ## User portal
21
23
 
22
24
  | Item | Routes below |
23
25
  |---|---|
24
26
  | `user-profile` | Profile: `/user/profile` |
25
27
  | `forgot-password` | Auth: forgot / reset password |
26
- | `account-security` | Auth: refresh, change password, 2FA, sessions (+ `Session`) |
28
+ | `account-security` | Auth: refresh, change password, TOTP/email OTP; 501 device-session extension points (+ `Session` model) |
27
29
  | `email-verification` | Auth: verify email |
28
30
  | `account-settings` | Profile: avatar, settings, account, dashboard, activity |
29
31
  | `notifications` | Notifications (+ `Notification`) |
@@ -106,3 +106,20 @@ Unhandled errors are logged at `error` with the request ID and full stack (`err`
106
106
  ## Shipping logs
107
107
 
108
108
  JSON lines on stdout is what log collectors (Datadog, Loki, CloudWatch, Vector) expect — no transport configuration needed. For custom pino transports, set `pretty: false` and pipe stdout.
109
+
110
+ ## Query metrics
111
+
112
+ Opt in with `logging: { queries: { metrics: true } }`, or `{ metrics: { maxEntries: 500 } }`. The default limit when enabled is 1000 distinct model/operation pairs per worker process; zero disables metrics. Logging and slow/N+1 options remain independent.
113
+
114
+ ```ts
115
+ import { getQueryMetrics, resetQueryMetrics } from 'express-file-cluster';
116
+
117
+ const snapshot = getQueryMetrics();
118
+ // { enabled, since, dropped, entries: [{ model, op, calls, errors, statements,
119
+ // totalMs, minMs, maxMs, meanMs, slow }] }
120
+ resetQueryMetrics(); // optional: start a fresh window without disabling collection
121
+ ```
122
+
123
+ Snapshots are detached from internal state and contain no SQL, parameter values, error details or request IDs. Each entry aggregates completed calls, failures, inclusive statement counts and durations in milliseconds. Nested model calls retain their own entries; their statements also count toward the outer operation, so summing entries is not a global database statement total. `slow` counts calls at or above `slowMs`.
124
+
125
+ When the entry limit is reached, existing pairs keep updating; observations for new pairs increment `dropped`. Reset/reconfiguration clears entries, dropped counts and the `since` timestamp. Metrics are off by default. These are per-process counters, not a cluster-wide service or an OpenTelemetry exporter; collect from each worker/instance separately and secure any diagnostic endpoint you add.
@@ -117,7 +117,9 @@ efc db pull --out pulled # somewhere else, to compare
117
117
  - **Indexes:** unique, plain, compound and text indexes.
118
118
  - **Relations:** foreign keys become `ref`s with `onDelete`. A column like `authorId` becomes an `author` field that keeps the `authorId` column. EFC join tables become many-to-many arrays, and every target model gets back-`relations`.
119
119
 
120
- A schema EFC created pulls back to models that sync finds nothing to change in. For a schema EFC didn't create, anything that has no EFC equivalent is noted at the top of the file: expression or partial indexes, other CHECKs, composite keys, and other defaults. Existing files are kept unless you pass `--force`.
120
+ A schema EFC created pulls back to models that sync finds nothing to change in. For a schema EFC didn't create, anything that has no EFC equivalent is noted at the top of the file: expression or partial indexes, other CHECKs, composite keys, and other defaults.
121
+
122
+ Models already in the output directory keep their names: a table one of them maps (`AuditLog` → `auditlogs`) is pulled under that name, so refs to it name it too, and it's never written to a second file. Existing files are kept unless you pass `--force`, which refreshes a model in its own `<Model>.ts` but never overwrites a model defined in another file, or a file whose name differs only in case (the same file on macOS and Windows).
121
123
 
122
124
  ## Pulling an existing database (MongoDB)
123
125
 
@@ -132,7 +134,7 @@ MongoDB has no schema to read, so `pull` samples each collection (`$sample`) and
132
134
  - **Required:** only when every sampled document had a non-null value. A field with mixed types (or only nulls) becomes `{ type: 'object' }` (any value) with a note.
133
135
  - **Refs:** an `objectId` field gets `ref` when its name matches another collection (`owner`, `ownerId` → `Owner`) or when every sampled id exists in exactly one other collection; otherwise a note asks you to add it.
134
136
  - **Indexes:** single-field unique, plain, `text`, `2dsphere` and `hashed` indexes go on the field; compound, partial and TTL indexes into `indexes`.
135
- - **Names and timestamps:** a model per collection (`audit_log` → `AuditLog`, with `collection: 'audit_log'` when mongoose wouldn't pick that name); `createdAt`/`updatedAt` dates map to the default `timestamps`, otherwise `timestamps: false`.
137
+ - **Names and timestamps:** a model per collection (`audit_log` → `AuditLog`, with `collection: 'audit_log'` when mongoose wouldn't pick that name); `createdAt`/`updatedAt` dates map to the default `timestamps`, otherwise `timestamps: false`. Existing models in the output directory keep their names here too, as for PostgreSQL.
136
138
 
137
139
  `_id` and `__v` are left to defineCollection. Read the generated files before using them: a sample shows what the data *has*, not what it must have.
138
140
 
@@ -0,0 +1,31 @@
1
+ # Testing file-based routes
2
+
3
+ `createTestApp()` from `express-file-cluster/testing` mounts your real route files on an Express app. Use it with supertest or another HTTP test harness. It shares the production HTTP middleware, router and error handler with `ignite()`, including JSON/form/cookie parsing, request context, validation, catch-all decoding and 405 handling.
4
+
5
+ ```ts
6
+ import { createTestApp } from 'express-file-cluster/testing';
7
+ import request from 'supertest';
8
+ import path from 'node:path';
9
+
10
+ const app = await createTestApp({
11
+ apiDir: path.resolve('src/api'),
12
+ auth: { secret: 'test-only-secret', strategy: 'bearer' },
13
+ });
14
+
15
+ const response = await request(app).get('/v1/api/health');
16
+ expect(response.status).toBe(200);
17
+ ```
18
+
19
+ Install the test harness in your app (`npm i -D supertest @types/supertest`). Your test runner must be able to import the route files: Configure the runner/loader to transform dynamically imported TypeScript routes when needed; a plain Node process can point at built JavaScript or use a TypeScript loader.
20
+
21
+ `apiDir` is required and must be an existing directory. It is specific to this helper; `ignite()` still discovers `src/api` by convention and has no `apiDir` option. Creating multiple apps does not change the working directory. Each app has its own router and middleware stack.
22
+
23
+ The helper returns an Express app without calling `listen()`, forking workers, scanning tasks, initializing database/cache/queue services, or adding signal handlers. It disables CORS and logging for tests and omits the development dashboard. Supertest can open its own temporary HTTP listener when making a request. For database and queue tests, configure real service fixtures separately, or use `ignite()` to exercise the complete boot lifecycle. The helper does not provide model mocks or an `enqueue()` implementation.
24
+
25
+ Authentication and logging are process-wide in EFC. The helper disables the process logger and configures auth when `auth` is supplied; use one auth configuration per test process, and isolate suites that require different secrets/strategies. Calling the helper without `auth` does not reset an existing auth configuration. Imported route modules follow normal module caching. Global model/cache/task state is not reset between apps.
26
+
27
+ See the [API reference](../api-reference/testing.md) for all options.
28
+
29
+ The CommonJS `/testing` entry delegates to the ESM helper using native `import()`, so dynamically imported ESM routes share its authentication and request context. The Node/runner must support the route files' module format.
30
+
31
+ The ESM and CommonJS builds share process-wide auth configuration, request AsyncLocalStorage and cache state. CommonJS `requireAuth` global middleware therefore sees helper auth options, preserves `getCurrentUser()` across awaits into ESM routes, and observes the same revocations. Model/queue fixtures are still configured separately.
@@ -2,7 +2,7 @@
2
2
 
3
3
  **express-file-cluster (EFC)** is an opinionated backend framework built on Express. It removes routing ceremony, saturates every CPU core automatically, and ships a production-grade background-task subsystem — all from a single `ignite()` call.
4
4
 
5
- > **Status: v0.10.0 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, migrations (written for you from model changes: `efc db generate`, plus `efc db pull` and `efc import-prisma`), and the `efc add` feature registry (auth, admin, billing… copied into your app as source you own) are all implemented.
5
+ > **Status: v0.10.2 — Beta.** File-based routing (incl. catch-all and optional segments), request validation, clustering, auth, structured logging, MongoDB and PostgreSQL models with types inferred from the schema, PostgreSQL-native `defineTable` (Prisma-style queries and relations: foreign keys, many-to-many, `include`, relation filters, nested writes), query logging, BullMQ and pg-boss tasks with cron and dead-letter tooling, migrations (written for you from model changes: `efc db generate`, plus `efc db pull` and `efc import-prisma`), and the `efc add` feature registry (auth, admin, billing… copied into your app as source you own) are all implemented.
6
6
 
7
7
  ---
8
8
 
@@ -47,6 +47,7 @@
47
47
  | [Migrations & Seeds](./guides/migrations.md) | `efc db generate / migrate / rollback / pull / seed / studio`, drift checks |
48
48
  | [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
49
49
  | [Coming from mongoose](./guides/coming-from-mongoose.md) | `defineCollection` for mongoose users: schema and query mapping |
50
+ | [Testing](./guides/testing.md) | `createTestApp` for real file-based routes without service boot |
50
51
  | [Validation](./guides/validation.md) | Route `schema` exports with zod, valibot, arktype |
51
52
  | [Logging](./guides/logging.md) | pino, request IDs, `getLogger()` |
52
53
  | [Caching & Sessions](./guides/caching.md) | `cache`, `cacheResponse`, revoking JWT sessions |
@@ -37,8 +37,12 @@ Load **only** the module the work points to. Each is self-contained.
37
37
  docs/ ← full documentation
38
38
  ```
39
39
 
40
- ## Status (v0.10.0 — Beta, Phase 2 complete + defineTable with relations + generated migrations + `efc add` registry)
40
+ ## Status (v0.10.2 — Beta, Phase 2 complete + defineTable with relations + generated migrations + `efc add` registry)
41
41
 
42
42
  Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only cookie + Bearer token auth (scrypt password hashing built in), structured logging (pino, request IDs), `defineModel` on MongoDB (mongoose) **and** PostgreSQL (Drizzle) with validation, query options, bulk ops, transactions, `sync()`/`drop()`, PostgreSQL-native `defineTable` (Prisma-style queries, foreign keys, many-to-many, `include`, relation filters, nested writes), MongoDB-native `defineCollection` (mongoose vocabulary, BSON types, geo/text, `bulkWrite`, change streams), query logging (`logging.queries`), BullMQ **and** pg-boss task backends with cron schedules and dead-letter CLI, worker_threads for CPU-bound tasks, migrations/seeds/studio (`efc db`) incl. migrations generated from model diffs (`efc db generate`), `efc db pull` and `efc import-prisma`, full CLI.
43
43
 
44
44
  **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`.
45
+
46
+ Phase 3 testing utilities: `createTestApp` from `express-file-cluster/testing` mounts a real route tree without service boot or a listener. Read `docs/guides/testing.md` and `docs/api-reference/testing.md`; see process-wide auth/logging isolation limits.
47
+
48
+ M6 completed 2026-10-30: query logging + bounded opt-in query metrics, editable studio, pool settings + bounded prepared statements, and a strict 10% nightly benchmark gate. See `bench/results/m6-validation.md` for measured evidence. OpenTelemetry is a separate Phase 3 task.
@@ -6,12 +6,13 @@ Source of truth: `packages/core/src/`. Do not invent exports, types, or sub-path
6
6
 
7
7
  ## Sub-path exports
8
8
 
9
- Three import paths. No others exist.
9
+ Four import paths. No others exist.
10
10
 
11
11
  ```ts
12
12
  import { ... } from 'express-file-cluster' // main
13
13
  import { ... } from 'express-file-cluster/auth' // auth module
14
14
  import { ... } from 'express-file-cluster/tasks' // tasks module
15
+ import { createTestApp } from 'express-file-cluster/testing' // test helper
15
16
  ```
16
17
 
17
18
  ---
@@ -25,7 +26,7 @@ Source: `packages/core/src/index.ts`
25
26
  ```ts
26
27
  async function ignite(config: EFCConfig): Promise<http.Server | undefined> // undefined on the cluster primary
27
28
  function gracefulShutdown(server: http.Server | undefined, timeoutMs?: number): void
28
- function compose(...handlers: RequestHandler[]): RequestHandler
29
+ function compose(...handlers: RequestHandler[]): RequestHandler // next(err) stops + forwards; next('route'|'router') passes to Express
29
30
 
30
31
  // Models — one API on MongoDB (mongoose) and PostgreSQL (Drizzle); engine picked at first use
31
32
  // Types are INFERRED from the schema literal — no interface needed:
@@ -69,6 +70,11 @@ function setDbClient(client: Record<string, unknown>): void
69
70
  function getDbClient(): Record<string, unknown>
70
71
 
71
72
  // Logging (pino)
73
+ function getQueryMetrics(): QueryMetricsSnapshot // per-process bounded aggregates, opt-in logging.queries.metrics
74
+ function resetQueryMetrics(): void // clears window without disabling collection
75
+ // QueryMetricsSnapshot: { enabled; since (epoch ms); dropped; entries: ReadonlyArray<QueryMetric> }
76
+ // QueryMetric: { model; op; calls; errors; statements; totalMs; minMs; maxMs; meanMs; slow }
77
+ // QueryMetric and QueryMetricsSnapshot are exported types. No SQL/params/error strings in snapshots.
72
78
  const logger: Logger // proxy for getLogger()
73
79
  function getLogger(): Logger // request-scoped child (carries reqId) inside a request, root otherwise
74
80
 
@@ -104,7 +110,7 @@ interface EFCConfig {
104
110
  dashboard?: boolean; // dev-only route docs at '/'
105
111
  database?: 'mongodb' | 'postgresql'; // default: inferred from databaseUrl scheme
106
112
  databaseUrl?: string;
107
- databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number }; // per worker
113
+ databasePool?: { max?: number; idleTimeoutMs?: number; connectionTimeoutMs?: number; preparedStatements?: boolean | { max?: number } }; // per worker
108
114
  authStrategy?: 'http-only' | 'bearer'; // default 'http-only'; 'localStorage' = old name for 'bearer'; anything else = bearer + warning (error in 1.0)
109
115
  jwtSecret?: string;
110
116
  jwtExpiresIn?: string; // default '7d'
@@ -141,7 +147,7 @@ interface LoggingConfig {
141
147
  level?: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'silent'; // default 'info'
142
148
  pretty?: boolean; // default: non-production TTY
143
149
  requests?: boolean; // default true
144
- queries?: boolean | { all?: boolean; slowMs?: number; nPlusOne?: number | false }; // default off; slowMs 500, nPlusOne 10
150
+ queries?: boolean | { all?: boolean; slowMs?: number; nPlusOne?: number | false; metrics?: boolean | { maxEntries?: number } }; // default off; slowMs 500, nPlusOne 10
145
151
  }
146
152
  ```
147
153
 
@@ -330,3 +336,13 @@ function listTasks(): ReadonlyArray<{ name: string; options: TaskOptions }>
330
336
  | `tasks.connectionString` (pg-boss) | — | `databaseUrl` |
331
337
 
332
338
  `NODE_ENV` is the sole exception — a Node/Express-wide runtime-mode signal, not an app secret — and is still read directly via `process.env['NODE_ENV']` in three places: `ignite()`'s cluster-in-production default, the dev-only dashboard toggle, and the `http-only` auth strategy's cookie `Secure` flag.
339
+
340
+ Generated app 2FA (not core exports): TOTP/email OTP enrollment, password+code login, disable. Init asks allowed methods (`TWO_FACTOR_METHOD`); each account chooses one. See `auth-internals.md` for endpoints, encrypted secrets, replay protection and OAuth limitations.
341
+
342
+ ## `express-file-cluster/testing` (Phase 3)
343
+
344
+ `async createTestApp(options: TestAppOptions): Promise<express.Express>`. Required `apiDir: string` (existing directory); optional `basePath` (default `/v1/api`), `globalMiddlewares`, `auth: { secret, strategy?, expiresIn?, cookieDomain? }` (defaults http-only/1h), `requestTimeout`, `trustProxy`, `onError`. Exports `TestAppOptions`. Real scanner/router/validation + shared production HTTP stack; no listen/cluster/services/tasks/signals/cwd mutation, CORS/logging/dashboard disabled. Auth/logging and module/model/cache/task state remain process-wide. `apiDir` is NOT an ignite option. See `api-reference/testing.md` and `guides/testing.md`.
345
+
346
+ Auth payloads may include `efc_auth_at` (epoch milliseconds from before credentials are read): revocation checks it conservatively against the account cutoff, capped at the server's issue time. Generated login/refresh routes set it. `/testing` supports CommonJS callers through an async bridge to its ESM implementation.
347
+
348
+ ESM/CJS auth configuration, request context and cache state are shared within the process, including mixed-module middleware in `/testing`. Generated reset-password uses atomic unexpired-token consumption and clears refresh credentials; custom auth logout propagates revocation failure.
@@ -16,7 +16,7 @@ configureAuth({
16
16
  })
17
17
  ```
18
18
 
19
- `_config` is a module-level singleton. All auth functions throw `'[EFC] Auth not configured — pass jwtSecret to ignite()'` if called before `configureAuth`.
19
+ Auth configuration is a process-wide singleton shared by the ESM and CommonJS builds. All auth functions throw `'[EFC] Auth not configured — pass jwtSecret to ignite()'` if called before `configureAuth`.
20
20
 
21
21
  ---
22
22
 
@@ -54,6 +54,14 @@ That's the entire implementation. Clears the cookie. The JWT itself is not inval
54
54
 
55
55
  ---
56
56
 
57
+ ## Generated account-security routes
58
+
59
+ `change-password` checks nonempty string inputs and the authenticated account's current password, hashes and persists the replacement, clears its stored refresh token and expiry, then calls `revokeAllSessions`. Both User and Admin accounts are supported. Success signs out existing access and refresh tokens, including the current access token; revocation errors propagate rather than reporting success. This is generated app code, not a new core auth API.
60
+
61
+ Generated 2FA is app code (`src/lib/two-factor` + routes), not a new core API. Init / `efc add account-security` asks `TWO_FACTOR_METHOD=totp|email|both`; init adds email-client/SMTP prompts for email/both. Users and admins enroll one allowed method. `POST /auth/2fa/setup` with `{ password, method }` starts enrollment (TOTP returns a Base32 secret + otpauthUrl, email returns 202 and queues a code); `{ password, method, code }` confirms. GET returns status/allowed methods only. Confirmation clears refresh credentials and calls `revokeAllSessions`. TOTP: RFC 6238 SHA-1, six digits, 30s ±1, atomic last-step comparison. Email: random six digits, 5m expiry, HMAC digest bound to purpose/account/address, atomic consume. Active/pending TOTP secrets use AES-256-GCM with account identity as AAD and independent 64-hex `TWO_FACTOR_KEY`. Strip active/pending secret, email hash/expiry/purpose and last-step fields from records.
62
+
63
+ Login and `/auth/2fa/verify` share the full password+factor flow and one account rate-limit bucket (10/15m, cache errors reject). No tokens until the factor succeeds; email without code sends only after password verification. Disable needs authentication + password + a fresh code (email without code requests a disable code), erases secrets, and revokes access/refresh tokens. Refresh rotation compare-and-sets old token + enabled state. OAuth rejects 2FA-enabled accounts (use password+code); password reset preserves 2FA. No recovery codes. Device-session list/revoke remain authenticated **501** extension points.
64
+
57
65
  ## Session revocation (`revokeSession`, `revokeAllSessions`) — needs `cache`
58
66
 
59
67
  Every signed token now carries `jti` (randomUUID), `iat`, and `efc_iat` (ms) — via the shared `sign()` used by
@@ -139,3 +147,8 @@ Format accepted by `jose`: `'15m'`, `'1h'`, `'7d'`, `'30d'`, integer seconds, et
139
147
  - No revocation without a `cache` configured (then `revokeToken` just clears the cookie and a copied token stays valid until it expires). With a cache: `revokeSession` / `revokeAllSessions`.
140
148
  - No CSRF token — relies on `SameSite: Strict` for http-only strategy.
141
149
  - No multi-strategy per-route override — `authStrategy` is global, set once in `ignite()`.
150
+
151
+
152
+ Generated User/Admin logout requires authentication, compare-and-sets the account's stored refresh token to empty (including bearer logout with no refresh cookie/body), then revokes the current access token and clears cookies. Login persists refresh credentials only while the password hash still matches its verified snapshot. Generated login/refresh tokens carry `efc_auth_at`, captured before credential reads; revocation rejects a token whose authentication started at or before the cutoff, even if it was signed afterwards. Custom token issuers may include this numeric epoch-millisecond claim for the same protection; it can only restrict access, never override a later server-issued time. Existing generated apps must update their owned auth routes as well as the framework to receive these fixes.
153
+
154
+ Password reset atomically consumes the matching, still-unexpired reset token while replacing the password and clearing stored refresh credentials and pending 2FA challenges. Concurrent use has one winner; expiry is rechecked in the database after hashing. Active 2FA enrollment remains enabled. Password changes also invalidate outstanding reset links. Custom auth-entity logout propagates revocation-store failures instead of returning a false success. Existing apps must update their owned reset-password, change-password, two-factor helper and custom logout files.
@@ -140,3 +140,9 @@ const clusterEnabled = config.cluster ?? (process.env['NODE_ENV'] === 'productio
140
140
  - `config.cluster: false` → **OFF** regardless of NODE_ENV
141
141
 
142
142
  `efc start dev` sets `NODE_ENV=development` → clustering is automatically off in dev.
143
+
144
+ ## PostgreSQL prepared statements (M6)
145
+
146
+ `databasePool.preparedStatements?: boolean | { max?: number }` defaults true/100 names per physical connection; false or max 0 disables (Mongo ignores). A private Pool/client proxy is passed to Drizzle, preserving Pool identity and transaction-client release; exported native `db` is unchanged. Object query configs for single SELECT/INSERT/UPDATE/DELETE/WITH statements get a SQL-shape hash name; parameters/types/rowMode are untouched, explicit names/control/DDL/multi-statements unchanged. Lifetime budget bounds server names, with unnamed fallback (no eviction/DEALLOCATE). Schema sync/drop bumps generation; connection budgets never reset. External DDL requires reconnecting, and incompatible poolers require opting out. `prepared-statements.integration.test.ts` proves reuse, transactions, budget/disable and schema invalidation.
147
+
148
+ `logging.queries.metrics: true | { maxEntries }` enables bounded per-process model/op aggregates (default off; enabled default 1000, zero disables). Main exports `getQueryMetrics`, `resetQueryMetrics`, `QueryMetric`, `QueryMetricsSnapshot`. Snapshots contain counters/latency summaries, since and dropped observations; no SQL/params/error details. Nested statement counts inclusive; reset/reconfigure starts a new window. Not distributed tracing.
@@ -22,7 +22,7 @@ scan.ts: filePathToUrlPath(relativePath)
22
22
 
23
23
  A catch-all must be the LAST segment — `[...slug]/edit.ts` throws at startup. Catch-all
24
24
  routes mount on a compiled RegExp (`RouteEntry.pattern`); a mapper restores named params,
25
- and catch-all values arrive as `string[]` (URI-decoded; `[]` when an optional one is empty).
25
+ and catch-all values arrive as `string[]` (`[]` when an optional one is empty). Split the raw path captures before decoding each segment once: `%2F` stays inside one array item, `%252F` becomes `%2F`, and `%25` becomes `%`. Never decode Express's already-decoded `req.params` again.
26
26
 
27
27
  ### Examples derived from the exact regex
28
28
 
@@ -17,7 +17,7 @@ import { ... } from 'express-file-cluster/config'
17
17
  import { ... } from 'express-file-cluster/models'
18
18
  ```
19
19
 
20
- Only three sub-paths exist: (no suffix), `/auth`, `/tasks`.
20
+ Four import paths exist: (no suffix), `/auth`, `/tasks`, `/testing`. `/testing` exports `createTestApp` and `TestAppOptions`; it does not boot services or mock databases/tasks.
21
21
 
22
22
  ---
23
23
 
@@ -26,6 +26,7 @@ Only three sub-paths exist: (no suffix), `/auth`, `/tasks`.
26
26
  ```ts
27
27
  // ❌ NOT exported from any EFC path
28
28
  createApp()
29
+ createTestApp() // ← EXISTS only from express-file-cluster/testing; apiDir is test-only
29
30
  createServer()
30
31
  useMiddleware()
31
32
  addRoute()
@@ -213,6 +214,13 @@ refreshToken() // does NOT exist as a core export
213
214
  // revokeToken(res) still ONLY clears the cookie.
214
215
  // ❌ No refresh-token rotation or session listing ("show my active devices") in core
215
216
 
217
+ // ✅ Generated 2FA supports TOTP/email OTP (init asks totp|email|both; each account chooses one).
218
+ // Enrollment/disable require current password; login verifies password + factor before tokens.
219
+ // Independent TWO_FACTOR_KEY encrypts secrets; codes are atomically consumed. This is app
220
+ // code, not a new core auth export. No recovery codes or automated lost-device recovery.
221
+ // ❌ Device-session list/revoke routes still return 501. Password changes DO verify
222
+ // the old password, persist a hash, and revoke access/refresh tokens.
223
+
216
224
  // ❌ No per-route strategy override
217
225
  // authStrategy is global — set once in ignite()
218
226
  ```
@@ -18,7 +18,7 @@ Deprecations are announced at least one minor release before removal, with a sta
18
18
  - **Major** (1.x → 2.0): breaking changes only, each with upgrade steps.
19
19
  - **Minor** (1.1 → 1.2): new features, backwards compatible.
20
20
  - **Patch** (1.1.0 → 1.1.1): fixes and security fixes only.
21
- - The three import paths (`express-file-cluster`, `/auth`, `/tasks`) and everything they export are the public API. Anything else — internal modules, generated file layouts, log message wording — can change in a minor.
21
+ - The four import paths (`express-file-cluster`, `/auth`, `/tasks`, `/testing`) and everything they export are the public API. Anything else — internal modules, generated file layouts, log message wording — can change in a minor.
22
22
 
23
23
  ## Long-term support (from 1.0)
24
24