express-file-cluster 0.3.15 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -33
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-3VWD2ZED.js +60 -0
- package/dist/chunk-3VWD2ZED.js.map +1 -0
- package/dist/chunk-47K2532L.cjs +196 -0
- package/dist/chunk-47K2532L.cjs.map +1 -0
- package/dist/chunk-5PDAWMGF.js +438 -0
- package/dist/chunk-5PDAWMGF.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-ALBDM5R3.cjs +60 -0
- package/dist/chunk-ALBDM5R3.cjs.map +1 -0
- package/dist/chunk-JJJJTACK.js +196 -0
- package/dist/chunk-JJJJTACK.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-M7MUPWCE.js +116 -0
- package/dist/chunk-M7MUPWCE.js.map +1 -0
- package/dist/chunk-PMF4GMHD.js +154 -0
- package/dist/chunk-PMF4GMHD.js.map +1 -0
- package/dist/chunk-QTRGJ2EN.cjs +2635 -0
- package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
- package/dist/chunk-RSBW2B3D.cjs +126 -0
- package/dist/chunk-RSBW2B3D.cjs.map +1 -0
- package/dist/chunk-RTFJ32T5.js +2635 -0
- package/dist/chunk-RTFJ32T5.js.map +1 -0
- package/dist/chunk-SFVEQ2T5.cjs +438 -0
- package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
- package/dist/chunk-SZT36SGB.cjs +154 -0
- package/dist/chunk-SZT36SGB.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-ULQXD4YZ.cjs +116 -0
- package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
- package/dist/chunk-VYHJX54R.js +126 -0
- package/dist/chunk-VYHJX54R.js.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +323 -0
- package/dist/docs/api-reference/table.md +250 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +70 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +308 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +289 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +472 -7
- package/dist/index.d.ts +472 -7
- package/dist/index.js +283 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
- package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
- package/dist/pgboss-backend-UUJOVEYK.js +14 -0
- package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-DJCPAsM4.d.cts +541 -0
- package/dist/types-DJCPAsM4.d.ts +541 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
|
@@ -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.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Caching & Sessions
|
|
2
|
+
|
|
3
|
+
`ignite({ cache })` gives you a key/value cache, response caching for GET routes, and the store `requireAuth` checks for **revoked sessions** — so logging out (or "log out everywhere") actually invalidates tokens.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Configure
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// efc.config.ts
|
|
11
|
+
const config: EFCConfig = {
|
|
12
|
+
cache: { backend: 'redis', url: process.env.REDIS_URL },
|
|
13
|
+
};
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
| Option | Backend | Default | |
|
|
17
|
+
|---|---|---|---|
|
|
18
|
+
| `backend` | — | — | `'redis'` (shared by all workers and instances) or `'memory'` (shared by this machine's workers) |
|
|
19
|
+
| `url` | redis | `redis://localhost:6379` | `rediss://`, ACL users and `/db` supported |
|
|
20
|
+
| `prefix` | both | `'efc:'` | Key prefix, so several apps can share one Redis |
|
|
21
|
+
| `timeout` | redis | `1000` | Per-command ms before Redis counts as unavailable |
|
|
22
|
+
| `maxEntries` | memory | `10000` | Least-recently-used entries are evicted beyond this |
|
|
23
|
+
| `onRevocationCheckError` | both | `'reject'` | What `requireAuth` does if it can't reach the cache — see [outage behaviour](#outage-behaviour) |
|
|
24
|
+
|
|
25
|
+
Requires `ioredis` for the Redis backend (`npm install ioredis` — BullMQ already depends on it).
|
|
26
|
+
|
|
27
|
+
**Memory backend under clustering.** The store lives in the cluster primary and workers reach it over IPC, so every worker on the machine sees the same entries and the same revoked sessions. It is still one machine's memory: not shared between instances behind a load balancer, and emptied on restart (revoked tokens become valid again). Use Redis once you run more than one instance. If workers are started by your own cluster primary instead of `ignite()`'s, there's no EFC primary to answer; each worker then logs a warning and keeps its own store.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## The `cache` API
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { cache } from 'express-file-cluster';
|
|
35
|
+
|
|
36
|
+
await cache.set('user:42', user, { ttl: 300 }); // seconds; omit for no expiry
|
|
37
|
+
const hit = await cache.get<User>('user:42'); // undefined on a miss
|
|
38
|
+
await cache.has('user:42');
|
|
39
|
+
await cache.del('user:42', 'user:43'); // → number deleted
|
|
40
|
+
await cache.clear('user:'); // every key with this prefix → number deleted
|
|
41
|
+
|
|
42
|
+
// Get-or-compute: concurrent callers in one process share a single computation
|
|
43
|
+
const stats = await cache.wrap('stats:daily', 60, () => Stats.aggregate(pipeline));
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Values are stored as JSON — `Date`s come back as ISO strings. `undefined` is never cached.
|
|
47
|
+
|
|
48
|
+
### When Redis is down
|
|
49
|
+
|
|
50
|
+
The cache **degrades instead of failing**: `get` returns `undefined`, `set`/`del` are no-ops, `wrap` just runs your function. Requests keep working (only slower), and a warning is logged at most every 30 seconds. Boot waits up to ~2 s for the first connection, then continues regardless.
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Response caching
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
// src/api/products/index.ts
|
|
58
|
+
import { cacheResponse } from 'express-file-cluster';
|
|
59
|
+
|
|
60
|
+
export const middlewares = [cacheResponse(60)]; // seconds
|
|
61
|
+
|
|
62
|
+
export const GET = async (req, res) => {
|
|
63
|
+
res.json(await Product.find({}, { sort: { name: 1 } }));
|
|
64
|
+
};
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
- Caches **200 JSON** responses of `GET`/`HEAD`; other methods and statuses pass through.
|
|
68
|
+
- Keyed by the full URL (path + query) — `?page=2` is a separate entry. Override with `key: (req) => …`.
|
|
69
|
+
- Adds `X-Cache: HIT` or `MISS`.
|
|
70
|
+
- Per-user data: put `requireAuth` first and use `perUser: true` — entries are keyed by the JWT's `sub`/`id`, and requests without a user skip the cache instead of sharing one.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
export const middlewares = [requireAuth, cacheResponse({ ttl: 30, perUser: true })];
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Invalidate after writes by prefix — cached responses live under `res:`:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
export const POST = async (req, res) => {
|
|
80
|
+
const product = await Product.create(req.body);
|
|
81
|
+
await cache.clear('res:/v1/api/products');
|
|
82
|
+
res.status(201).json(product);
|
|
83
|
+
};
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Session revocation
|
|
89
|
+
|
|
90
|
+
JWTs are stateless, so on their own a token stays valid until it expires — clearing the cookie doesn't help if the token was copied. With a cache configured, every token EFC signs carries a unique `jti`, and `requireAuth` checks a denylist:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { requireAuth, revokeSession, revokeAllSessions } from 'express-file-cluster/auth';
|
|
94
|
+
|
|
95
|
+
// Log out this device: the current token is rejected from now until it would have expired.
|
|
96
|
+
export const middlewares = [requireAuth];
|
|
97
|
+
export const POST = async (req, res) => {
|
|
98
|
+
await revokeSession(req, res); // `res` also clears the cookie (http-only strategy)
|
|
99
|
+
res.json({ ok: true });
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// Log out everywhere / after a password change: every token issued to this user
|
|
103
|
+
// before now is rejected; tokens issued afterwards work.
|
|
104
|
+
await revokeAllSessions(user.id); // the JWT's `sub` or `id` claim
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Entries expire on their own once the tokens they cover would have expired (`jwtExpiresIn`), so the denylist never grows unbounded.
|
|
108
|
+
|
|
109
|
+
### Outage behaviour
|
|
110
|
+
|
|
111
|
+
If `requireAuth` can't reach the cache to check a token, `onRevocationCheckError` decides:
|
|
112
|
+
|
|
113
|
+
| Value | Authenticated requests during the outage | |
|
|
114
|
+
|---|---|---|
|
|
115
|
+
| `'reject'` (default) | **503** `{ "error": "Service Unavailable" }` | A revoked token can never slip through. 503 rather than 401, so clients don't discard tokens and force a re-login over a blip. |
|
|
116
|
+
| `'allow'` | pass through | Availability first — revocations made before the outage apply again once the cache is back. |
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
cache: { backend: 'redis', url: process.env.REDIS_URL, onRevocationCheckError: 'allow' },
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
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.
|
|
123
|
+
|
|
124
|
+
`revokeToken(res)` still exists and only clears the cookie — prefer `revokeSession` when a cache is configured.
|