express-file-cluster 0.3.15 → 0.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 (116) hide show
  1. package/README.md +71 -33
  2. package/dist/auth/index.cjs +12 -2
  3. package/dist/auth/index.cjs.map +1 -1
  4. package/dist/auth/index.d.cts +13 -2
  5. package/dist/auth/index.d.ts +13 -2
  6. package/dist/auth/index.js +12 -2
  7. package/dist/chunk-277BSYVH.js +127 -0
  8. package/dist/chunk-277BSYVH.js.map +1 -0
  9. package/dist/chunk-6OGOVV57.js +3847 -0
  10. package/dist/chunk-6OGOVV57.js.map +1 -0
  11. package/dist/chunk-7YEX4MQV.cjs +38 -0
  12. package/dist/chunk-7YEX4MQV.cjs.map +1 -0
  13. package/dist/chunk-AZYXQU3Z.cjs +3847 -0
  14. package/dist/chunk-AZYXQU3Z.cjs.map +1 -0
  15. package/dist/chunk-BUBXO7WU.js +170 -0
  16. package/dist/chunk-BUBXO7WU.js.map +1 -0
  17. package/dist/chunk-LJNSJFOL.js +38 -0
  18. package/dist/chunk-LJNSJFOL.js.map +1 -0
  19. package/dist/chunk-MGH4VDV3.cjs +170 -0
  20. package/dist/chunk-MGH4VDV3.cjs.map +1 -0
  21. package/dist/chunk-R34R7QPD.cjs +116 -0
  22. package/dist/chunk-R34R7QPD.cjs.map +1 -0
  23. package/dist/chunk-RS4MXCPW.js +116 -0
  24. package/dist/chunk-RS4MXCPW.js.map +1 -0
  25. package/dist/chunk-T4OHFU5T.cjs +154 -0
  26. package/dist/chunk-T4OHFU5T.cjs.map +1 -0
  27. package/dist/chunk-TI24L4XE.cjs.map +1 -1
  28. package/dist/chunk-TRC4DUZB.js +438 -0
  29. package/dist/chunk-TRC4DUZB.js.map +1 -0
  30. package/dist/chunk-TYR2GZZE.cjs +196 -0
  31. package/dist/chunk-TYR2GZZE.cjs.map +1 -0
  32. package/dist/chunk-UBQYQPBU.js +154 -0
  33. package/dist/chunk-UBQYQPBU.js.map +1 -0
  34. package/dist/chunk-UTM4PEVG.js +196 -0
  35. package/dist/chunk-UTM4PEVG.js.map +1 -0
  36. package/dist/chunk-YL37D6KM.cjs +127 -0
  37. package/dist/chunk-YL37D6KM.cjs.map +1 -0
  38. package/dist/chunk-ZDM5JHVK.cjs +438 -0
  39. package/dist/chunk-ZDM5JHVK.cjs.map +1 -0
  40. package/dist/cli/db-runner.cjs +497 -0
  41. package/dist/cli/db-runner.cjs.map +1 -0
  42. package/dist/cli/db-runner.d.cts +2 -0
  43. package/dist/cli/db-runner.d.ts +2 -0
  44. package/dist/cli/db-runner.js +497 -0
  45. package/dist/cli/db-runner.js.map +1 -0
  46. package/dist/cli/index.cjs +447 -69
  47. package/dist/cli/index.cjs.map +1 -1
  48. package/dist/cli/index.js +473 -95
  49. package/dist/cli/index.js.map +1 -1
  50. package/dist/docs/api-reference/auth.md +232 -0
  51. package/dist/docs/api-reference/compose.md +78 -0
  52. package/dist/docs/api-reference/db.md +351 -0
  53. package/dist/docs/api-reference/http-error.md +109 -0
  54. package/dist/docs/api-reference/ignite.md +326 -0
  55. package/dist/docs/api-reference/table.md +458 -0
  56. package/dist/docs/api-reference/tasks.md +140 -0
  57. package/dist/docs/cli/db.md +38 -0
  58. package/dist/docs/cli/diagnostics.md +145 -0
  59. package/dist/docs/cli/generate.md +120 -0
  60. package/dist/docs/cli/index.md +48 -0
  61. package/dist/docs/cli/start.md +112 -0
  62. package/dist/docs/contributing/index.md +139 -0
  63. package/dist/docs/core-concepts/background-tasks.md +228 -0
  64. package/dist/docs/core-concepts/clustering.md +114 -0
  65. package/dist/docs/core-concepts/file-based-routing.md +235 -0
  66. package/dist/docs/core-concepts/index.md +79 -0
  67. package/dist/docs/core-concepts/middleware.md +144 -0
  68. package/dist/docs/getting-started/index.md +91 -0
  69. package/dist/docs/getting-started/project-structure.md +154 -0
  70. package/dist/docs/guides/ai-agents.md +48 -0
  71. package/dist/docs/guides/authentication.md +196 -0
  72. package/dist/docs/guides/caching.md +124 -0
  73. package/dist/docs/guides/database.md +217 -0
  74. package/dist/docs/guides/deployment.md +171 -0
  75. package/dist/docs/guides/environment-variables.md +106 -0
  76. package/dist/docs/guides/error-handling.md +172 -0
  77. package/dist/docs/guides/generated-portals.md +115 -0
  78. package/dist/docs/guides/logging.md +108 -0
  79. package/dist/docs/guides/mailer.md +166 -0
  80. package/dist/docs/guides/migrations.md +106 -0
  81. package/dist/docs/guides/rbac.md +89 -0
  82. package/dist/docs/guides/validation.md +95 -0
  83. package/dist/docs/index.md +93 -0
  84. package/dist/docs/skills/SKILL.md +44 -0
  85. package/dist/docs/skills/api-surface.md +309 -0
  86. package/dist/docs/skills/auth-internals.md +141 -0
  87. package/dist/docs/skills/pre-flight.md +142 -0
  88. package/dist/docs/skills/routing-rules.md +114 -0
  89. package/dist/docs/skills/tasks-internals.md +172 -0
  90. package/dist/docs/skills/what-not-to-invent.md +251 -0
  91. package/dist/index.cjs +264 -391
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +699 -7
  94. package/dist/index.d.ts +699 -7
  95. package/dist/index.js +258 -385
  96. package/dist/index.js.map +1 -1
  97. package/dist/pgboss-backend-QKBXVJ6B.js +14 -0
  98. package/dist/pgboss-backend-QKBXVJ6B.js.map +1 -0
  99. package/dist/pgboss-backend-TCHI7CHM.cjs +14 -0
  100. package/dist/pgboss-backend-TCHI7CHM.cjs.map +1 -0
  101. package/dist/tasks/index.cjs.map +1 -1
  102. package/dist/tasks/index.d.cts +1 -1
  103. package/dist/tasks/index.d.ts +1 -1
  104. package/dist/types-B6lVw4bj.d.cts +588 -0
  105. package/dist/types-B6lVw4bj.d.ts +588 -0
  106. package/package.json +28 -5
  107. package/dist/chunk-6522HS2J.cjs +0 -99
  108. package/dist/chunk-6522HS2J.cjs.map +0 -1
  109. package/dist/chunk-DGVOJNR6.cjs +0 -55
  110. package/dist/chunk-DGVOJNR6.cjs.map +0 -1
  111. package/dist/chunk-KOHLLUN7.js +0 -55
  112. package/dist/chunk-KOHLLUN7.js.map +0 -1
  113. package/dist/chunk-VIP3PFWZ.js +0 -99
  114. package/dist/chunk-VIP3PFWZ.js.map +0 -1
  115. package/dist/types-BusbSenn.d.cts +0 -162
  116. package/dist/types-BusbSenn.d.ts +0 -162
@@ -0,0 +1,144 @@
1
+ # Middleware
2
+
3
+ EFC supports three tiers of middleware. Each tier has a distinct scope — pick the right tier and you never apply middleware more broadly than you intend.
4
+
5
+ ---
6
+
7
+ ## Tier 1 — Global middleware
8
+
9
+ Configured in `ignite()`. Applied to **every** incoming request, before any route is matched.
10
+
11
+ ```ts
12
+ import rateLimit from 'express-rate-limit';
13
+
14
+ ignite({
15
+ globalMiddlewares: [
16
+ rateLimit({ windowMs: 60_000, max: 100 }),
17
+ ],
18
+ });
19
+ ```
20
+
21
+ > **CORS is built-in.** EFC applies its own CORS middleware based on the `cors` option in `ignite()` (see [`ignite()` reference](../api-reference/ignite.md#cors)). You do not need to pass a `cors()` call here — doing so would create a duplicate header.
22
+
23
+ ---
24
+
25
+ ## Tier 2 — Route-level middleware
26
+
27
+ Export a `middlewares` array from a route file. Applied to every handler exported from that file, after global middleware.
28
+
29
+ ```ts
30
+ // src/api/admin/users.ts
31
+ import { requireAuth } from 'express-file-cluster/auth';
32
+ import { authorize } from '../../middlewares/authorize';
33
+
34
+ export const middlewares = [requireAuth, authorize('admin')];
35
+
36
+ export const GET = async (req, res) => {
37
+ // Only reachable after requireAuth + authorize('admin') pass
38
+ res.json({ users: [] });
39
+ };
40
+
41
+ export const DELETE = async (req, res) => {
42
+ // Same guard applies here automatically
43
+ res.status(204).send();
44
+ };
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Tier 3 — Handler-level middleware (`compose`)
50
+
51
+ `compose(...handlers)` wraps a single handler with one or more middleware functions. Use it for guards that apply to exactly one method in a file.
52
+
53
+ ```ts
54
+ // src/api/users/index.ts
55
+ import { compose } from 'express-file-cluster';
56
+ import { validateBody } from '../../middlewares/validation';
57
+ import { CreateUserSchema } from '../../schemas/user';
58
+
59
+ export const GET = async (req, res) => {
60
+ res.json({ users: [] });
61
+ };
62
+
63
+ // Only POST gets body validation
64
+ export const POST = compose(
65
+ validateBody(CreateUserSchema),
66
+ async (req, res) => {
67
+ // req.body is guaranteed valid here
68
+ res.status(201).json({ id: 'new-id' });
69
+ },
70
+ );
71
+ ```
72
+
73
+ ---
74
+
75
+ ## How `compose` works
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)`.
78
+
79
+ ```ts
80
+ export function compose(...handlers: RequestHandler[]): RequestHandler {
81
+ return (req, res, next) => {
82
+ let index = 0;
83
+
84
+ function dispatch(i: number): void {
85
+ if (i >= handlers.length) { next(); return; }
86
+ const handler = handlers[i];
87
+ try {
88
+ Promise.resolve(handler(req, res, () => dispatch(i + 1))).catch(next);
89
+ } catch (err) {
90
+ next(err);
91
+ }
92
+ }
93
+
94
+ dispatch(index);
95
+ };
96
+ }
97
+ ```
98
+
99
+ ---
100
+
101
+ ## Middleware execution order
102
+
103
+ For a request that hits `POST /users` on a file that has both `export const middlewares` and a `compose` handler:
104
+
105
+ ```
106
+ global middlewares (ignite)
107
+ ↓
108
+ route-level middlewares (export const middlewares = [...])
109
+ ↓
110
+ handler-level middlewares (compose(mw1, mw2, handler))
111
+ ↓
112
+ the actual handler function
113
+ ```
114
+
115
+ ---
116
+
117
+ ## Writing a middleware
118
+
119
+ EFC middleware is a plain Express `RequestHandler`:
120
+
121
+ ```ts
122
+ // src/middlewares/authorize.ts
123
+ import type { Request, Response, NextFunction } from 'express';
124
+
125
+ export function authorize(role: string) {
126
+ return (req: Request, res: Response, next: NextFunction): void => {
127
+ const user = (req as any).user;
128
+ if (user?.role !== role) {
129
+ res.status(403).json({ error: 'Forbidden' });
130
+ return;
131
+ }
132
+ next();
133
+ };
134
+ }
135
+ ```
136
+
137
+ Scaffold a middleware file with the CLI:
138
+
139
+ ```bash
140
+ efc generate middleware authorize
141
+ # → src/middlewares/authorize.ts
142
+ ```
143
+
144
+ > Route-level role protection doesn't need a custom middleware like `authorize` above — `requireAuth` itself accepts role names: `requireAuth('admin')`. `create-efc-app`'s **RBAC** feature option scaffolds routes that use this shorthand (plus a `Role` model) instead of an inline guard. See [RBAC](../guides/rbac.md).
@@ -0,0 +1,91 @@
1
+ # Getting Started
2
+
3
+ ## Prerequisites
4
+
5
+ - Node.js 18 or later
6
+ - npm 9 or later
7
+ - (Optional) MongoDB or Redis if you need a database or background tasks
8
+
9
+ ---
10
+
11
+ ## Scaffold a new project
12
+
13
+ ```bash
14
+ npx create-efc-app my-api
15
+ ```
16
+
17
+ The interactive wizard walks through:
18
+
19
+ ```
20
+ ? Project name: my-api
21
+ ? Language: TypeScript | JavaScript
22
+ ? Database: MongoDB | PostgreSQL
23
+ ? Authentication strategy: http-only | localStorage
24
+ ? Features: (space to toggle)
25
+ ◉ Multi-core clustering
26
+ ◉ Background tasks
27
+ ◉ API route documentation
28
+ ◉ User portal
29
+ ◉ Admin portal
30
+ ◉ Role-based access control
31
+ ◯ Mailer
32
+ ```
33
+
34
+ Generated models and routes are identical for both databases — `defineModel` compiles to mongoose or Drizzle at runtime. See [Database](../guides/database.md).
35
+
36
+ Depending on what you toggle on, you'll see follow-up questions:
37
+
38
+ - **Background tasks** → pick a queue backend: `BullMQ` (Redis — `REDIS_URL` in `.env`) or `pg-boss` (stores jobs in your PostgreSQL, no Redis to run).
39
+ - **Mailer** → pick an email provider: `Gmail` (preconfigured `smtp.gmail.com`, no host/port to type) or `Other (custom SMTP)` (asks for host + port). Either way you're then asked for the sending email address and password. **For Gmail this must be a 16-character App Password, not your normal Gmail password** — the prompt validates the length and rejects anything that isn't 16 characters. See [Mailer](../guides/mailer.md) for the full walkthrough, including how to generate an App Password.
40
+ - **User portal / Admin portal** → scaffold a large set of ready-made models and routes (auth, profile, billing, support tickets, admin dashboard, content management, etc.). See [Generated Portals](../guides/generated-portals.md) for the complete list.
41
+ - **Role-based access control** → generates a `Role` model and swaps every protected route's `middlewares` export to use the `requireAuth('role')` shorthand instead of an inline guard. See [RBAC](../guides/rbac.md).
42
+
43
+ After confirmation it:
44
+
45
+ 1. Writes the full project tree (see [Project Structure](./project-structure.md)).
46
+ 2. Creates `efc.config.ts` pre-configured for your choices.
47
+ 3. Generates `.env` (gitignored, `JWT_SECRET` pre-filled with `openssl rand -hex 64`, plus `SMTP_*` vars if you enabled the mailer) and `.env.example` (committed, documented placeholders).
48
+ 4. Adds `.env` to `.gitignore`.
49
+ 5. Writes `package.json` lifecycle scripts (`dev`, `build`, `start`, `test`, `db:migrate`, `db:rollback`, `db:seed`, `db:studio`).
50
+ 6. With a User or Admin portal, writes `src/migrations/00000000000000_init` that creates every generated model's table/collection and indexes.
51
+ 7. Runs `npm install` with the dependencies for your selections, then installs the `efc` CLI globally.
52
+
53
+ ---
54
+
55
+ ## Generated `package.json` scripts
56
+
57
+ | Script | Expands to | When to use |
58
+ |---|---|---|
59
+ | `npm run dev` | `efc start dev` | Local development — hot-reload, single process |
60
+ | `npm run build` | `efc build prod` | CI/CD — type-check + compile to `dist/` |
61
+ | `npm start` | `efc start prod` | Production — runs `dist/` with clustering |
62
+ | `npm test` | `efc run tests` | Test suite via Vitest |
63
+ | `npm run db:migrate` | `efc db migrate` | Apply pending migrations |
64
+ | `npm run db:rollback` | `efc db rollback` | Revert the last migration batch |
65
+ | `npm run db:seed` | `efc db seed` | Run seed scripts |
66
+ | `npm run db:studio` | `efc db studio` | Browse the database (read-only) |
67
+
68
+ ---
69
+
70
+ ## First run
71
+
72
+ ```bash
73
+ cd my-api
74
+ npm run dev # tables / indexes are created on first use — no migration needed
75
+ # 12:00:01 INFO [primary] Worker primary listening on :3000
76
+ ```
77
+
78
+ The server is live at `http://localhost:3000`. The scaffolder creates a `src/api/health.ts` route at `/health` as a smoke test.
79
+
80
+ ---
81
+
82
+ ## Next steps
83
+
84
+ - [Project Structure](./project-structure.md) — understand every file the scaffolder created.
85
+ - [File-Based Routing](../core-concepts/file-based-routing.md) — learn the naming rules.
86
+ - [Generated Portals](../guides/generated-portals.md) — full model/route inventory if you enabled User or Admin portal.
87
+ - [RBAC](../guides/rbac.md) — role-based route protection.
88
+ - [Mailer](../guides/mailer.md) — Gmail app-password and custom SMTP setup.
89
+ - [Migrations & Seeds](../guides/migrations.md) — evolving the schema.
90
+ - [Validation](../guides/validation.md) — `export const schema` with zod & co.
91
+ - [CLI Reference](../cli/index.md) — all `efc` commands.
@@ -0,0 +1,154 @@
1
+ # Project Structure
2
+
3
+ A scaffolded EFC project looks like this:
4
+
5
+ ```
6
+ my-api/
7
+ ├── src/
8
+ │ ├── api/ # HTTP routes — every file here is a route
9
+ │ │ ├── health.ts # GET /health
10
+ │ │ ├── auth/
11
+ │ │ │ ├── login.ts # POST /auth/login
12
+ │ │ │ ├── logout.ts # POST /auth/logout
13
+ │ │ │ └── register.ts # POST /auth/register (if userPortal)
14
+ │ │ └── users/
15
+ │ │ ├── index.ts # GET /users • POST /users
16
+ │ │ └── [id].ts # GET /users/:id • DELETE /users/:id
17
+ │ ├── tasks/ # Background jobs (scanned non-recursively)
18
+ │ │ └── SendEmail.ts # task name: "SendEmail"
19
+ │ ├── model/ # Engine-agnostic data models
20
+ │ │ ├── User.ts
21
+ │ │ └── Role.ts # generated if the RBAC option is enabled
22
+ │ ├── migrations/ # efc db migrate — run in filename order
23
+ │ │ └── 00000000000000_init.ts # syncs every generated model
24
+ │ ├── seeds/ # efc db seed (create with efc generate seed)
25
+ │ └── index.ts # Framework entry point
26
+ ├── efc.config.ts # Structural configuration
27
+ ├── .env # Real secrets — gitignored
28
+ ├── .env.example # Documented template — safe to commit
29
+ ├── .gitignore
30
+ ├── package.json
31
+ └── tsconfig.json
32
+ ```
33
+
34
+ If you enable the **User portal**, **Admin portal**, **RBAC**, or **Mailer** options during scaffolding, `src/model/`, `src/api/`, and `src/tasks/` fill out considerably — see [Generated Portals](../guides/generated-portals.md) for the full list of models and routes, [RBAC](../guides/rbac.md) for the `requireAuth('role')` shorthand, and [Mailer](../guides/mailer.md) for the SMTP setup.
35
+
36
+ ---
37
+
38
+ ## `src/api/` — Route modules
39
+
40
+ `src/api/` is a fixed convention, not a configurable option — EFC resolves it automatically (checking `src/api`, then `api`, then `dist/api` for compiled output). Every `.ts` (or `.js`) file inside it becomes a route. The URL path is derived from the file path relative to `src/api/`:
41
+
42
+ | File | URL |
43
+ |---|---|
44
+ | `api/health.ts` | `/health` |
45
+ | `api/users/index.ts` | `/users` |
46
+ | `api/users/[id].ts` | `/users/:id` |
47
+ | `api/posts/[slug]/comments.ts` | `/posts/:slug/comments` |
48
+
49
+ Files named `index.ts` inside a directory map to the directory's URL (no `/index` suffix).
50
+ `[bracket]` segments become Express `:param` segments.
51
+
52
+ See [File-Based Routing](../core-concepts/file-based-routing.md) for the complete rule set.
53
+
54
+ ---
55
+
56
+ ## `src/tasks/` — Background task modules
57
+
58
+ `src/tasks/` is likewise a fixed convention. It is scanned **non-recursively** — subdirectories are not processed. Every file directly inside it registers a named background task; the task name is the file's basename without extension:
59
+
60
+ | File | Task name |
61
+ |---|---|
62
+ | `tasks/SendEmail.ts` | `"SendEmail"` |
63
+ | `tasks/ResizeImage.ts` | `"ResizeImage"` |
64
+
65
+ Tasks must export a default `TaskDefinition` created with `defineTask()`.
66
+
67
+ See [Background Tasks](../core-concepts/background-tasks.md).
68
+
69
+ ---
70
+
71
+ ## `src/model/` — Data models
72
+
73
+ Engine-agnostic model definitions using `defineModel()` — they compile to a mongoose model on MongoDB or a Drizzle table on PostgreSQL, with the same API on both.
74
+
75
+ See [Database Guide](../guides/database.md).
76
+
77
+ ---
78
+
79
+ ## `src/migrations/` and `src/seeds/`
80
+
81
+ Migration files export `up()` / `down()` and run in filename order with `efc db migrate` / `efc db rollback`; seeds export a default function and run with `efc db seed`. Both are loaded from `src/` under `tsx` in development and from `dist/src/` in production. See [Migrations & Seeds](../guides/migrations.md).
82
+
83
+ ---
84
+
85
+ ## `src/index.ts` — Entry point
86
+
87
+ The single call that boots the framework:
88
+
89
+ ```ts
90
+ import { ignite, gracefulShutdown } from 'express-file-cluster';
91
+
92
+ ignite({
93
+ // cluster defaults to NODE_ENV === 'production' — don't hardcode true here, or
94
+ // dev mode clusters too (an explicit boolean always wins over that default)
95
+ workers: 2,
96
+ tasks: { backend: 'bullmq' },
97
+ })
98
+ .then(gracefulShutdown)
99
+ .catch(console.error);
100
+ ```
101
+
102
+ `ignite()` does **not** read `PORT`, `DATABASE_URL`, `JWT_SECRET`, or `CORS_ORIGINS` from `process.env` automatically — pass them explicitly (see `efc.config.ts` below; `NODE_ENV` is the sole exception). `src/api/` and `src/tasks/` are resolved by convention, not passed as options — there is no `apiDir`/`tasksDir` config.
103
+
104
+ See [`ignite()` API reference](../api-reference/ignite.md).
105
+
106
+ ---
107
+
108
+ ## `efc.config.ts` — where every runtime value is wired
109
+
110
+ `ignite()` never reads `process.env` itself for app config (the one exception is `NODE_ENV`, a Node/Express-wide runtime-mode signal — see [Environment Variables](../guides/environment-variables.md#precedence)). The scaffolder generates a typed config file that reads `.env` explicitly and builds the object `ignite()` receives — both structural choices (auth strategy, task backend) and runtime values (port, database URL, JWT secret, CORS origins, ...) live here:
111
+
112
+ ```ts
113
+ import type { EFCConfig } from 'express-file-cluster';
114
+
115
+ // The framework never reads process.env itself — every runtime value it needs is read
116
+ // here, explicitly, and passed in. Edit .env to change values; edit this file to change
117
+ // which env vars are wired up or add new ones.
118
+ const corsOrigins = process.env.CORS_ORIGINS
119
+ ? process.env.CORS_ORIGINS.split(',').map((o) => o.trim()).filter(Boolean)
120
+ : undefined;
121
+
122
+ const config: EFCConfig = {
123
+ port: process.env.PORT ? Number(process.env.PORT) : undefined,
124
+ databaseUrl: process.env.DATABASE_URL,
125
+ jwtSecret: process.env.JWT_SECRET,
126
+ jwtExpiresIn: process.env.JWT_EXPIRES_IN,
127
+ cookieDomain: process.env.COOKIE_DOMAIN,
128
+ cors: corsOrigins ? { origin: corsOrigins } : true,
129
+ authStrategy: 'http-only',
130
+ tasks: { backend: 'bullmq', concurrency: 5, redisUrl: process.env.REDIS_URL },
131
+ globalMiddlewares: [],
132
+ };
133
+
134
+ export default config;
135
+ ```
136
+
137
+ `ignite()` itself does **not** auto-load `efc.config.ts` — `src/index.ts` is the actual runtime entrypoint. The generated `src/index.ts` imports `efc.config.ts` and spreads its fields into `ignite()`, so this file is the single source of truth for what's actually applied:
138
+
139
+ ```ts
140
+ import { ignite, gracefulShutdown } from 'express-file-cluster';
141
+ import config from '../efc.config.js';
142
+
143
+ ignite({ ...config }).then(gracefulShutdown).catch(console.error);
144
+ ```
145
+
146
+ The scaffolded `tsconfig.json` includes `efc.config.ts` alongside `src/**/*` so this import typechecks without a `rootDir` violation.
147
+
148
+ ---
149
+
150
+ ## `.env` and `.env.example`
151
+
152
+ `.env` is gitignored and holds real secrets. `.env.example` is committed and documents every required variable with placeholder values.
153
+
154
+ See [Environment Variables](../guides/environment-variables.md) for the full variable reference.
@@ -0,0 +1,48 @@
1
+ # AI Coding Agents
2
+
3
+ EFC's API is newer than most models' training data, so an agent writing EFC code from memory will
4
+ invent imports, options and methods. EFC ships its documentation where agents can read it.
5
+
6
+ ---
7
+
8
+ ## Docs inside the package
9
+
10
+ Every release of `express-file-cluster` carries its own docs:
11
+
12
+ ```
13
+ node_modules/express-file-cluster/dist/docs/
14
+ ├── index.md, getting-started/, core-concepts/, guides/, api-reference/, cli/
15
+ └── skills/ ← dense reference cards: api-surface, routing-rules, what-not-to-invent, …
16
+ ```
17
+
18
+ They always match the installed version. Apps created with `create-efc-app` include an
19
+ **`AGENTS.md`** that tells agents (Claude Code, Codex, Cursor, Copilot, …) to read these first.
20
+ For an existing app, copy the idea: point your agent at `skills/api-surface.md`,
21
+ `skills/what-not-to-invent.md` and the guide for the task at hand.
22
+
23
+ ---
24
+
25
+ ## MCP server
26
+
27
+ `express-file-cluster-mcp` serves the same docs over the
28
+ [Model Context Protocol](https://modelcontextprotocol.io), with search and scaffolding tools:
29
+
30
+ ```bash
31
+ claude mcp add efc -- npx -y express-file-cluster-mcp
32
+ ```
33
+
34
+ Other clients:
35
+
36
+ ```json
37
+ { "mcpServers": { "efc": { "command": "npx", "args": ["-y", "express-file-cluster-mcp"] } } }
38
+ ```
39
+
40
+ | Tool | Use |
41
+ |---|---|
42
+ | `get-rules` | the public API, valid import paths, things that don't exist — call first |
43
+ | `list-docs` / `get-doc` / `search-docs` | find and read pages |
44
+ | `resolve-route` | route file → URL pattern |
45
+ | `scaffold-route` / `scaffold-task` | generate files that follow the conventions |
46
+
47
+ Pages are also resources (`efc://docs/guides/database`, …), and prompts such as `efc-model` and
48
+ `efc-debug` point the agent at the pages that answer them.
@@ -0,0 +1,196 @@
1
+ # Authentication Guide
2
+
3
+ EFC ships a complete JWT authentication system. Choose between two delivery strategies depending on your frontend architecture.
4
+
5
+ ---
6
+
7
+ ## Choosing a strategy
8
+
9
+ | | `http-only` | `localStorage` |
10
+ |---|---|---|
11
+ | **Token location** | `HttpOnly` cookie | Response body → client storage |
12
+ | **XSS risk** | Immune (JS can't read the cookie) | Exposed (JS reads `localStorage`) |
13
+ | **CSRF risk** | Mitigated by `SameSite=Strict` | Not applicable (no cookie) |
14
+ | **Best for** | SSR / SSG frontends, same-origin SPAs | SPAs on a different origin, mobile apps |
15
+ | **`requireAuth` reads from** | `req.cookies.efc_token` | `Authorization: Bearer` header |
16
+
17
+ Configure the strategy in `ignite()`:
18
+
19
+ ```ts
20
+ ignite({ authStrategy: 'http-only' }); // default
21
+ ignite({ authStrategy: 'localStorage' });
22
+ ```
23
+
24
+ ---
25
+
26
+ ## `http-only` strategy
27
+
28
+ ### Login
29
+
30
+ ```ts
31
+ // src/api/auth/login.ts
32
+ import type { Request, Response } from 'express';
33
+ import { issueToken } from 'express-file-cluster/auth';
34
+ import { User } from '../../model/User.js';
35
+
36
+ export const POST = async (req: Request, res: Response) => {
37
+ const user = await User.findOne({ email: req.body.email });
38
+ if (!user || !verifyPassword(req.body.password, user.passwordHash)) {
39
+ throw new HttpError(401, 'Invalid credentials');
40
+ }
41
+
42
+ await issueToken(res, { sub: user.id, role: user.role });
43
+ res.json({ message: 'Logged in' });
44
+ };
45
+ ```
46
+
47
+ `issueToken` sets a cookie named `efc_token`:
48
+
49
+ ```
50
+ Set-Cookie: efc_token=<jwt>; Path=/; HttpOnly; Secure; SameSite=Strict
51
+ ```
52
+
53
+ In development (`NODE_ENV !== 'production'`), `Secure` is omitted so the cookie works over `http://localhost`.
54
+
55
+ ### Logout
56
+
57
+ ```ts
58
+ // src/api/auth/logout.ts
59
+ import type { Request, Response } from 'express';
60
+ import { requireAuth, revokeSession } from 'express-file-cluster/auth';
61
+
62
+ export const middlewares = [requireAuth];
63
+
64
+ export const POST = async (req: Request, res: Response) => {
65
+ await revokeSession(req, res); // invalidates the token and clears the cookie
66
+ res.json({ message: 'Logged out' });
67
+ };
68
+ ```
69
+
70
+ `revokeSession` needs a `cache` in `ignite()` — projects from `create-efc-app` configure one (Redis when `REDIS_URL` is set, otherwise the in-memory store), and their logout and password-reset routes already revoke sessions. Without one, `revokeToken(res)` clears the cookie only — the token itself stays valid until it expires. `revokeAllSessions(userId)` logs a user out of every device. See [Caching & Sessions](./caching.md).
71
+
72
+ ### Protecting routes
73
+
74
+ ```ts
75
+ // src/api/profile.ts
76
+ import { requireAuth } from 'express-file-cluster/auth';
77
+
78
+ export const middlewares = [requireAuth];
79
+
80
+ export const GET = async (req, res) => {
81
+ const user = (req as any).user; // decoded JWT payload
82
+ res.json({ userId: user.sub, role: user.role });
83
+ };
84
+ ```
85
+
86
+ ---
87
+
88
+ ## `localStorage` strategy
89
+
90
+ ### Login
91
+
92
+ ```ts
93
+ // src/api/auth/login.ts
94
+ import type { Request, Response } from 'express';
95
+ import { signToken } from 'express-file-cluster/auth';
96
+ import { User } from '../../model/User.js';
97
+
98
+ export const POST = async (req: Request, res: Response) => {
99
+ const user = await User.findOne({ email: req.body.email });
100
+ if (!user || !verifyPassword(req.body.password, user.passwordHash)) {
101
+ throw new HttpError(401, 'Invalid credentials');
102
+ }
103
+
104
+ const token = await signToken({ sub: user.id, role: user.role });
105
+ res.json({ token });
106
+ };
107
+ ```
108
+
109
+ The client stores the token:
110
+
111
+ ```js
112
+ // frontend
113
+ const { token } = await fetch('/auth/login', { method: 'POST', body: ... }).then(r => r.json());
114
+ localStorage.setItem('authToken', token);
115
+ ```
116
+
117
+ And attaches it on protected requests:
118
+
119
+ ```js
120
+ fetch('/profile', {
121
+ headers: { Authorization: `Bearer ${localStorage.getItem('authToken')}` },
122
+ });
123
+ ```
124
+
125
+ ### Protecting routes
126
+
127
+ Identical to `http-only` — `requireAuth` reads from the correct source based on the configured strategy:
128
+
129
+ ```ts
130
+ export const middlewares = [requireAuth];
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Custom token payload
136
+
137
+ The `payload` object you pass to `issueToken` or `signToken` becomes the JWT body. Standard JWT claims (`sub`, `iat`, `exp`, `iss`, `aud`) are valid; you can add any custom fields.
138
+
139
+ ```ts
140
+ await issueToken(res, {
141
+ sub: user.id,
142
+ role: user.role,
143
+ plan: user.subscriptionPlan,
144
+ orgId: user.organizationId,
145
+ });
146
+ ```
147
+
148
+ If you want route protection based on the `role` claim, pass role names to `requireAuth`: `requireAuth('admin')` verifies the token *and* checks `payload.role` is one of the given roles, returning `403 Forbidden` otherwise. See [RBAC](./rbac.md).
149
+
150
+ Access custom claims in protected handlers via `(req as any).user`:
151
+
152
+ ```ts
153
+ export const GET = async (req, res) => {
154
+ const { sub, role, plan } = (req as any).user;
155
+ res.json({ sub, role, plan });
156
+ };
157
+ ```
158
+
159
+ ---
160
+
161
+ ## Token lifetime
162
+
163
+ Set `JWT_EXPIRES_IN` in `.env`, then pass it through as `jwtExpiresIn: process.env.JWT_EXPIRES_IN` in `efc.config.ts` (`ignite()` never reads it directly). Default: `7d`.
164
+
165
+ ```
166
+ JWT_EXPIRES_IN=15m # short-lived — for high-security use cases
167
+ JWT_EXPIRES_IN=1h
168
+ JWT_EXPIRES_IN=7d # default
169
+ JWT_EXPIRES_IN=30d
170
+ ```
171
+
172
+ There is currently no refresh-token mechanism built into the framework itself. For long-lived sessions with short-lived tokens, implement a `/auth/refresh` route that issues a new token using the existing one as a credential — if you enabled **User portal** during scaffolding (with MongoDB), a working `POST /auth/refresh` route is already generated for you: it stores a rotating long-lived refresh token in the database and reads it from an `efc_refresh_token` cookie or the `refreshToken` body field (see [Generated Portals](./generated-portals.md)).
173
+
174
+ ---
175
+
176
+ ## Cookie domain
177
+
178
+ For multi-subdomain setups (e.g. `api.example.com` setting a cookie for `*.example.com`), set:
179
+
180
+ ```
181
+ COOKIE_DOMAIN=.example.com
182
+ ```
183
+
184
+ and pass it through as `cookieDomain: process.env.COOKIE_DOMAIN` in `efc.config.ts` — `ignite()` never reads `COOKIE_DOMAIN` itself.
185
+
186
+ ---
187
+
188
+ ## Environment variables
189
+
190
+ | Variable | Wired into (via `efc.config.ts`) | Description |
191
+ |---|---|---|
192
+ | `JWT_SECRET` | `jwtSecret` | Signing key — must be set; generate with `openssl rand -hex 64` |
193
+ | `JWT_EXPIRES_IN` | `jwtExpiresIn` | Token lifetime — default `7d` |
194
+ | `COOKIE_DOMAIN` | `cookieDomain` | Cookie domain for `http-only` strategy |
195
+
196
+ `ignite()` doesn't read any of these from `process.env` itself — see the full [Environment Variables reference](./environment-variables.md) for how the scaffolded `efc.config.ts` wires them.