express-file-cluster 0.9.0 → 0.9.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 (87) hide show
  1. package/dist/auth/index.cjs +8 -2
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +13 -2
  4. package/dist/auth/index.d.ts +13 -2
  5. package/dist/auth/index.js +9 -3
  6. package/dist/{chunk-2J3HHQKP.cjs → chunk-ANUSWEAP.cjs} +55 -2
  7. package/dist/chunk-ANUSWEAP.cjs.map +1 -0
  8. package/dist/{chunk-RSZB7VAO.js → chunk-ATL4GYFU.js} +54 -1
  9. package/dist/chunk-ATL4GYFU.js.map +1 -0
  10. package/dist/{chunk-2PBMLMO4.js → chunk-QKQZF573.js} +26 -4
  11. package/dist/chunk-QKQZF573.js.map +1 -0
  12. package/dist/{chunk-6QNLN6AI.js → chunk-RRQ2RK5M.js} +353 -3
  13. package/dist/chunk-RRQ2RK5M.js.map +1 -0
  14. package/dist/{chunk-RGTENTDN.cjs → chunk-RTF7PHS2.cjs} +432 -82
  15. package/dist/chunk-RTF7PHS2.cjs.map +1 -0
  16. package/dist/{chunk-66R7S7J3.cjs → chunk-X2US4RAM.cjs} +26 -4
  17. package/dist/chunk-X2US4RAM.cjs.map +1 -0
  18. package/dist/cli/db-runner.cjs +17 -17
  19. package/dist/cli/db-runner.js +2 -2
  20. package/dist/cli/index.cjs +315 -26
  21. package/dist/cli/index.cjs.map +1 -1
  22. package/dist/cli/index.js +295 -6
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/docs/api-reference/auth.md +35 -0
  25. package/dist/docs/api-reference/collection.md +155 -0
  26. package/dist/docs/cli/add.md +36 -7
  27. package/dist/docs/guides/authentication.md +80 -4
  28. package/dist/docs/guides/coming-from-mongoose.md +60 -0
  29. package/dist/docs/guides/which-api.md +21 -12
  30. package/dist/docs/index.md +4 -2
  31. package/dist/docs/skills/SKILL.md +3 -3
  32. package/dist/docs/skills/api-surface.md +16 -0
  33. package/dist/docs/skills/what-not-to-invent.md +3 -2
  34. package/dist/index.cjs +18 -16
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +193 -3
  37. package/dist/index.d.ts +193 -3
  38. package/dist/index.js +5 -3
  39. package/dist/index.js.map +1 -1
  40. package/dist/registry/index.json +1 -1
  41. package/dist/registry/js-mongo/admin-users.json +1 -1
  42. package/dist/registry/js-mongo/auth.json +1 -1
  43. package/dist/registry/js-mongo/auth@apple.json +1 -1
  44. package/dist/registry/js-mongo/auth@google.json +1 -1
  45. package/dist/registry/js-mongo/email-client.json +1 -1
  46. package/dist/registry/js-mongo/forgot-password.json +1 -1
  47. package/dist/registry/js-pg-model/admin-users.json +1 -1
  48. package/dist/registry/js-pg-model/auth.json +1 -1
  49. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  50. package/dist/registry/js-pg-model/auth@google.json +1 -1
  51. package/dist/registry/js-pg-model/email-client.json +1 -1
  52. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  53. package/dist/registry/js-pg-table/admin-users.json +1 -1
  54. package/dist/registry/js-pg-table/auth.json +1 -1
  55. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  56. package/dist/registry/js-pg-table/auth@google.json +1 -1
  57. package/dist/registry/js-pg-table/email-client.json +1 -1
  58. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  59. package/dist/registry/ts-mongo/admin-users.json +1 -1
  60. package/dist/registry/ts-mongo/auth.json +1 -1
  61. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  62. package/dist/registry/ts-mongo/auth@google.json +1 -1
  63. package/dist/registry/ts-mongo/email-client.json +1 -1
  64. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  65. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  66. package/dist/registry/ts-pg-model/auth.json +1 -1
  67. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  68. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  69. package/dist/registry/ts-pg-model/email-client.json +1 -1
  70. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  71. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  72. package/dist/registry/ts-pg-table/auth.json +1 -1
  73. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  74. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  75. package/dist/registry/ts-pg-table/email-client.json +1 -1
  76. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  77. package/dist/tasks/index.d.cts +1 -1
  78. package/dist/tasks/index.d.ts +1 -1
  79. package/dist/{types-gyvA7BtO.d.ts → types-BY-ObnZH.d.cts} +36 -7
  80. package/dist/{types-gyvA7BtO.d.cts → types-BY-ObnZH.d.ts} +36 -7
  81. package/package.json +3 -3
  82. package/dist/chunk-2J3HHQKP.cjs.map +0 -1
  83. package/dist/chunk-2PBMLMO4.js.map +0 -1
  84. package/dist/chunk-66R7S7J3.cjs.map +0 -1
  85. package/dist/chunk-6QNLN6AI.js.map +0 -1
  86. package/dist/chunk-RGTENTDN.cjs.map +0 -1
  87. package/dist/chunk-RSZB7VAO.js.map +0 -1
@@ -11,6 +11,9 @@ import {
11
11
  signToken,
12
12
  requireAuth,
13
13
  getCurrentUser,
14
+ hashPassword,
15
+ verifyPassword,
16
+ passwordNeedsRehash,
14
17
  } from 'express-file-cluster/auth';
15
18
  ```
16
19
 
@@ -219,6 +222,38 @@ This is also what powers the `'$currentUser'` / `'$currentUser.<key>'` `defineMo
219
222
 
220
223
  ---
221
224
 
225
+ ## `hashPassword()` / `verifyPassword()` / `passwordNeedsRehash()`
226
+
227
+ Password hashing on `node:crypto`'s scrypt — no native addon and no extra dependency. These don't
228
+ need `jwtSecret`; they work anywhere.
229
+
230
+ ```ts
231
+ function hashPassword(password: string): Promise<string>
232
+ function verifyPassword(password: string, hash: string): Promise<boolean>
233
+ function passwordNeedsRehash(hash: string): boolean
234
+ ```
235
+
236
+ - `hashPassword` uses a random 16-byte salt and N=2^15, r=8, p=1 (32 MiB, a 64-byte key) and returns
237
+ `scrypt$<N>$<r>$<p>$<salt base64>$<key base64>`. It throws on an empty password. The password is
238
+ NFKC-normalised first, so the same characters typed differently hash the same.
239
+ - `verifyPassword` compares in constant time. It returns `false` for a wrong password or a malformed
240
+ hash, and also for cost parameters far above the defaults (N > 2^20, r > 32 or p > 16), so a planted
241
+ hash can't tie up a worker.
242
+ - **bcrypt hashes are not supported.** EFC has no bcrypt fallback (no `bcrypt`, no `bcryptjs`):
243
+ `verifyPassword` returns `false` for `$2a$` / `$2b$` / `$2y$` hashes (from apps scaffolded before
244
+ 0.9.2) and logs a warning. Those accounts sign in again after a password reset, which stores a
245
+ `hashPassword()` hash.
246
+ - `passwordNeedsRehash` is `true` for any hash not made with the current defaults. Check it after a
247
+ successful login and store a fresh `hashPassword()` result.
248
+
249
+ ```ts
250
+ const user = await User.findOne({ email });
251
+ if (!user || !(await verifyPassword(password, user.password))) throw new HttpError(401, 'Invalid credentials');
252
+ if (passwordNeedsRehash(user.password)) await User.update(user.id, { password: await hashPassword(password) });
253
+ ```
254
+
255
+ ---
256
+
222
257
  ## Token lifetime
223
258
 
224
259
  Controlled by the `JWT_EXPIRES_IN` environment variable. Default: `7d`.
@@ -0,0 +1,155 @@
1
+ # defineCollection — API Reference
2
+
3
+ `defineCollection` is the MongoDB-native model API. It uses mongoose's vocabulary (`find` with projections, `findOneAndUpdate`, `bulkWrite`, aggregation pipelines, change streams) and adds BSON types. It runs on the same foundation as `defineModel`: schema format, inferred types, validation, auto-sync, `transaction()`, `efc db generate`. Underneath, it is a mongoose model.
4
+
5
+ Building on PostgreSQL? Use [`defineTable`](./table.md). Need one model for both engines? Use [`defineModel`](./db.md). See [Which model API?](../guides/which-api.md).
6
+
7
+ ```ts
8
+ import { defineCollection, type InferRecord } from 'express-file-cluster';
9
+
10
+ export const Place = defineCollection('Place', {
11
+ name: { type: 'string', required: true },
12
+ location: { type: 'geoPoint', index: '2dsphere' },
13
+ price: { type: 'decimal128' }, // '19.99', exact
14
+ visits: { type: 'long', default: 0 }, // bigint
15
+ tags: { type: 'array', of: 'string', default: [] },
16
+ owner: { type: 'objectId', ref: 'User' },
17
+ reviews: [{ rating: { type: 'number', required: true, min: 1, max: 5 }, text: { type: 'string' } }],
18
+ }, { indexes: [{ fields: { name: 'text' } }] });
19
+
20
+ export type Place = InferRecord<typeof Place>;
21
+
22
+ const near = await Place.find(
23
+ { location: { $near: { $geometry: { type: 'Point', coordinates: [85.32, 27.71] }, $maxDistance: 2000 } } },
24
+ { projection: { name: 1 }, limit: 10 },
25
+ );
26
+ await Place.findOneAndUpdate({ name }, { $inc: { visits: 1 } }, { upsert: true, returnDocument: 'after' });
27
+ ```
28
+
29
+ Using a `defineCollection` model on a PostgreSQL connection fails at its first query, with an `[EFC]` error naming the model.
30
+
31
+ ---
32
+
33
+ ## Field types
34
+
35
+ Every `defineModel` field type and option works (`string`, `number`, `boolean`, `date`, `objectId`, embedded objects and arrays, `required`, `default`, `enum`, `min`/`max`, `match`, `validate`, `ref`, `sequence`, `renamedFrom`). On top of them:
36
+
37
+ | Type | Stored as | In records |
38
+ |---|---|---|
39
+ | `decimal128` | `Decimal128` | `string` (exact, `'19.99'`); writes take strings or numbers |
40
+ | `long` | `Long` (int64) | `bigint`, whatever the size; writes take bigints or numbers |
41
+ | `geoPoint` | GeoJSON `{ type: 'Point', coordinates: [lng, lat] }` | `GeoPoint`; longitude first, both checked for range |
42
+ | `binary` | `Binary` | `Buffer` |
43
+
44
+ The PostgreSQL types (`integer`, `bigint`, `decimal`, `uuid`, `json`) and `defineTable` options are refused at definition, with an `[EFC]` error naming the field.
45
+
46
+ `index` takes `true`, or a special index: `'2dsphere'` (geo), `'text'` or `'hashed'`. In `options.indexes`, field values can also be `'2dsphere'` and `'hashed'`, and an index can be partial:
47
+
48
+ ```ts
49
+ { indexes: [
50
+ { fields: { name: 'text', description: 'text' } },
51
+ { fields: { email: 1 }, unique: true, partialFilterExpression: { deletedAt: { $exists: false } } },
52
+ { fields: { expiresAt: 1 }, expireAfterSeconds: 0 }, // TTL
53
+ ] }
54
+ ```
55
+
56
+ ## Options
57
+
58
+ `ModelOptions` (`timestamps`, `indexes`, `collection`) plus:
59
+
60
+ | Option | |
61
+ |---|---|
62
+ | `collation` | default collation for queries and aggregations, e.g. `{ locale: 'en', strength: 2 }` (case-insensitive) |
63
+
64
+ ---
65
+
66
+ ## Reading
67
+
68
+ ```ts
69
+ find(filter?, options?): Promise<Record[]>
70
+ findOne(filter?, options?): Promise<Record | null>
71
+ findById(id, options?): Promise<Record | null> // malformed id → null
72
+ exists(filter): Promise<boolean>
73
+ countDocuments(filter?): Promise<number>
74
+ estimatedDocumentCount(): Promise<number> // from metadata: fast, no filter
75
+ distinct(field, filter?): Promise<value[]> // arrays are unwound, as in MongoDB
76
+ ```
77
+
78
+ | `options` | |
79
+ |---|---|
80
+ | `projection` | `{ name: 1 }` (only these, plus `id`) or `{ secret: 0 }` (all but these) |
81
+ | `sort` | `{ createdAt: -1, name: 'asc' }`, or `{ score: { $meta: 'textScore' } }` |
82
+ | `skip`, `limit` | |
83
+ | `populate` | `ref` fields to replace with the referenced documents |
84
+ | `collation` | overrides the model's |
85
+
86
+ Filters are MongoDB query documents: every query operator works (`$near`, `$geoWithin`, `$text`, `$elemMatch`, `$regex`, `$expr`, …), as do dotted paths. `id` is accepted for `_id`. Field values are type-checked against the record; dotted paths and operators are not.
87
+
88
+ ## Writing
89
+
90
+ ```ts
91
+ create(data): Promise<Record>
92
+ insertMany(data[]): Promise<Record[]>
93
+ updateOne(filter, update, { upsert? }): Promise<WriteResult>
94
+ updateMany(filter, update, { upsert? }): Promise<WriteResult>
95
+ replaceOne(filter, replacement, { upsert? }): Promise<WriteResult>
96
+ findOneAndUpdate(filter, update, { upsert?, returnDocument?, projection?, sort? }): Promise<Record | null>
97
+ findByIdAndUpdate(id, update, { returnDocument? }): Promise<Record | null>
98
+ findOneAndDelete(filter, { sort? }): Promise<Record | null>
99
+ findByIdAndDelete(id): Promise<Record | null>
100
+ deleteOne(filter): Promise<{ deletedCount }>
101
+ deleteMany(filter?): Promise<{ deletedCount }>
102
+ bulkWrite(ops, { ordered? }): Promise<BulkResult>
103
+ ```
104
+
105
+ - `WriteResult` is `{ matchedCount, modifiedCount, upsertedCount, upsertedId }`.
106
+ - As in mongoose, `findOneAndUpdate` returns the document **before** the update unless you pass `returnDocument: 'after'`.
107
+ - Updates take plain fields (shorthand for `$set`) or any update operator (`$set $unset $inc $mul $min $max $push $pull $addToSet $pop $rename $setOnInsert $currentDate`).
108
+ - **Writes are validated**: creates against the whole schema, updates on the fields they change (`runValidators`). Failures throw `ModelValidationError` (400 with `issues`). A duplicate on a unique index is an `HttpError` 409.
109
+ - `bulkWrite` takes `insertOne`, `updateOne`, `updateMany`, `replaceOne`, `deleteOne` and `deleteMany` operations, and returns `{ insertedCount, matchedCount, modifiedCount, deletedCount, upsertedCount }`.
110
+
111
+ ```ts
112
+ await Place.bulkWrite([
113
+ { insertOne: { document: { name: 'Patan' } } },
114
+ { updateOne: { filter: { name: 'Boudha' }, update: { $addToSet: { tags: 'stupa' } }, upsert: true } },
115
+ { deleteMany: { filter: { visits: { $lt: 1 } } } },
116
+ ]);
117
+ ```
118
+
119
+ ## Aggregation
120
+
121
+ ```ts
122
+ const ratings = await Place.aggregate<{ _id: string; avg: number }>([
123
+ { $unwind: '$reviews' },
124
+ { $group: { _id: '$name', avg: { $avg: '$reviews.rating' } } },
125
+ { $sort: { avg: -1 } },
126
+ ]);
127
+ ```
128
+
129
+ The pipeline is passed to MongoDB unchanged; type the output with the generic. Results get the same conversions as records: decimals become strings, longs bigints, `_id` gains a string `id`. `$lookup` joins other collections by collection name.
130
+
131
+ ## Change streams
132
+
133
+ ```ts
134
+ const stream = Place.watch([{ $match: { operationType: 'insert' } }]);
135
+ for await (const change of stream) {
136
+ console.log(change.operationType, change.id, change.fullDocument?.name);
137
+ if (done) break; // or: await stream.close()
138
+ }
139
+ ```
140
+
141
+ Each change has `operationType`, `id` (the document's), `fullDocument` (inserts and replaces; updates with `{ fullDocument: 'updateLookup' }`), `updateDescription` and `raw` (the driver's event). Change streams need a replica set.
142
+
143
+ ## Transactions
144
+
145
+ Calls inside `transaction(async () => { … })` join it, as with `defineModel`. MongoDB transactions need a replica set.
146
+
147
+ ## Sync and migrations
148
+
149
+ The same as `defineModel` on MongoDB. On first use the collection and its indexes are created (`autoSync`). `efc db sync [--dry-run]` reconciles indexes, and `efc db generate` writes migrations for index changes and `renamedFrom` fields.
150
+
151
+ ## Also
152
+
153
+ - `raw()`: the mongoose `Model`, for anything not covered here.
154
+ - `sync({ dryRun? })`, `drop()`.
155
+ - Types: `InferRecord<typeof Place>`, `InferCreate<typeof Place>`, `CollectionFilter<R>`, `CollectionUpdate<R>`.
@@ -34,6 +34,7 @@ efc diff # compare installed features with the regi
34
34
  | `--overwrite` | Replace files you've changed with the registry version |
35
35
  | `--no-install` | Don't run `npm install` / `pnpm install` / … afterwards |
36
36
  | `--no-prompt` | Don't ask the items' questions — write placeholders to `.env` instead |
37
+ | `--entity <name>` | Scaffold a custom authenticatable entity (model + namespaced auth routes) |
37
38
 
38
39
  ---
39
40
 
@@ -66,13 +67,41 @@ efc diff # compare installed features with the regi
66
67
 
67
68
  The full route list is in [Generated Portals](../guides/generated-portals.md); OAuth setup is in [Sign in with Google & Apple](../guides/oauth.md).
68
69
 
69
- A few things hold for every item:
70
+ ---
71
+
72
+ ## Custom auth entities
73
+
74
+ While `efc add auth` scaffolds the standard **User** and **Admin** principals, real-world apps (marketplaces, food delivery, logistics) often need custom entities like `Merchant`, `Driver`, `Seller`, or `DeliveryPartner`.
75
+
76
+ EFC provides a first-class shortcut to scaffold an authenticatable entity with its own model and namespaced routes:
77
+
78
+ ```bash
79
+ # Any of these syntaxes work:
80
+ efc add auth --entity merchant
81
+ efc add auth:merchant
82
+ efc add auth new merchant
83
+
84
+ # Multiple entities at once:
85
+ efc add auth:merchant auth:delivery-partner
86
+ ```
87
+
88
+ ### What gets generated
89
+
90
+ For `efc add auth:merchant`:
91
+
92
+ | File | Purpose |
93
+ |---|---|
94
+ | `src/model/Merchant.ts` | Model with `name`, `email`, `password`, `role: 'merchant'`, `isActive`, tokens |
95
+ | `src/api/auth/merchant/register.ts` | `POST /auth/merchant/register` |
96
+ | `src/api/auth/merchant/login.ts` | `POST /auth/merchant/login` (issues token with `role: 'merchant'`) |
97
+ | `src/api/auth/merchant/logout.ts` | `POST /auth/merchant/logout` |
98
+ | `src/api/auth/merchant/me.ts` | `GET /auth/merchant/me` (guarded by `requireAuth('merchant')`) |
99
+
100
+ - **No existing routes modified:** Existing `/auth/login` and `/auth/register` remain untouched.
101
+ - **Model registered:** On PostgreSQL with `defineTable`, registers the model in `src/model/index.ts`.
102
+ - **No extra packages:** Passwords are hashed with `hashPassword` / `verifyPassword` from `express-file-cluster/auth` (scrypt, built into Node).
103
+ - **Tracked in efc.json:** Recorded as `auth:<slug>` in `efc.json`.
70
104
 
71
- - **Dependencies come along.** `efc add admin-users` also installs `auth` and `admin` if they're missing.
72
- - **Routes that send email** (`auth`, `forgot-password`, `email-verification`) enqueue the `SendEmail` task. The base app has a stub that logs the message. `efc add email-client` swaps in real SMTP. These items need a task backend (`tasks` in `efc.config`); the base app always has one.
73
- - **Models shared by two items** (`Plan`, `SupportTicket`, `Notification`) are identical in both. The second item skips the file that's already there.
74
- - **On PostgreSQL with `defineTable`**, references are real foreign keys, and `efc add` registers new models in `src/model/index.ts` (the export plus the `Tables` entry). Models declare no back-relations. Add `relations: { … }` to a model when you want `include`. See [defineTable](../api-reference/table.md).
75
- - **Tables and collections** are created on first use (`autoSync`). With `autoSync: false`, run `efc db sync` or write a migration.
76
105
 
77
106
  ---
78
107
 
@@ -111,7 +140,7 @@ Wrong answers are asked again. A question is only asked for a variable the app d
111
140
 
112
141
  ```json
113
142
  {
114
- "registry": "0.9.0",
143
+ "registry": "0.9.2",
115
144
  "language": "typescript",
116
145
  "database": "postgresql",
117
146
  "modelApi": "defineTable",
@@ -32,12 +32,13 @@ ignite({ authStrategy: 'localStorage' });
32
32
  ```ts
33
33
  // src/api/auth/login.ts
34
34
  import type { Request, Response } from 'express';
35
- import { issueToken } from 'express-file-cluster/auth';
35
+ import { HttpError } from 'express-file-cluster';
36
+ import { issueToken, verifyPassword } from 'express-file-cluster/auth';
36
37
  import { User } from '../../model/User.js';
37
38
 
38
39
  export const POST = async (req: Request, res: Response) => {
39
40
  const user = await User.findOne({ email: req.body.email });
40
- if (!user || !verifyPassword(req.body.password, user.passwordHash)) {
41
+ if (!user || !(await verifyPassword(req.body.password, user.passwordHash))) {
41
42
  throw new HttpError(401, 'Invalid credentials');
42
43
  }
43
44
 
@@ -46,6 +47,8 @@ export const POST = async (req: Request, res: Response) => {
46
47
  };
47
48
  ```
48
49
 
50
+ `user.passwordHash` holds a string from `hashPassword()` — see [Passwords](#passwords).
51
+
49
52
  `issueToken` sets a cookie named `efc_token`:
50
53
 
51
54
  ```
@@ -94,12 +97,13 @@ export const GET = async (req, res) => {
94
97
  ```ts
95
98
  // src/api/auth/login.ts
96
99
  import type { Request, Response } from 'express';
97
- import { signToken } from 'express-file-cluster/auth';
100
+ import { HttpError } from 'express-file-cluster';
101
+ import { signToken, verifyPassword } from 'express-file-cluster/auth';
98
102
  import { User } from '../../model/User.js';
99
103
 
100
104
  export const POST = async (req: Request, res: Response) => {
101
105
  const user = await User.findOne({ email: req.body.email });
102
- if (!user || !verifyPassword(req.body.password, user.passwordHash)) {
106
+ if (!user || !(await verifyPassword(req.body.password, user.passwordHash))) {
103
107
  throw new HttpError(401, 'Invalid credentials');
104
108
  }
105
109
 
@@ -187,6 +191,55 @@ and pass it through as `cookieDomain: process.env.COOKIE_DOMAIN` in `efc.config.
187
191
 
188
192
  ---
189
193
 
194
+ ## Custom auth entities
195
+
196
+ EFC ships with **User** and **Admin** as built-in principals (`efc add auth`). Many apps need additional authenticatable entities — a food delivery app might have `Merchant` and `DeliveryPartner`, a marketplace might have `Seller` and `Buyer`.
197
+
198
+ Use `efc add auth:` to scaffold a new entity with its own model and namespaced auth routes:
199
+
200
+ ```bash
201
+ # Either syntax works:
202
+ efc add auth:merchant
203
+ efc add auth --entity merchant
204
+
205
+ # Multiple at once:
206
+ efc add auth:merchant auth:driver
207
+ ```
208
+
209
+ ### What gets generated
210
+
211
+ For `efc add auth:merchant`:
212
+
213
+ | File | Purpose |
214
+ |---|---|
215
+ | `src/model/Merchant.ts` | Model with name, email, password, role, isActive, tokens |
216
+ | `src/api/auth/merchant/register.ts` | `POST /auth/merchant/register` |
217
+ | `src/api/auth/merchant/login.ts` | `POST /auth/merchant/login` |
218
+ | `src/api/auth/merchant/logout.ts` | `POST /auth/merchant/logout` |
219
+ | `src/api/auth/merchant/me.ts` | `GET /auth/merchant/me` |
220
+
221
+ The generated code uses the same auth primitives (`issueToken`, `requireAuth`, `revokeSession`) as the built-in User/Admin. Each entity's JWT carries `role: 'merchant'` (or whatever the entity name is, lowercased).
222
+
223
+ ### Protecting routes by entity
224
+
225
+ ```ts
226
+ import { requireAuth } from 'express-file-cluster/auth';
227
+
228
+ // Only merchants can access this route:
229
+ export const middlewares = [requireAuth('merchant')];
230
+
231
+ // Merchants OR admins:
232
+ export const middlewares = [requireAuth('merchant', 'admin')];
233
+ ```
234
+
235
+ ### Customising the generated code
236
+
237
+ The files belong to you — they're copied into your `src/` just like `efc add auth`. Add fields to the model, change the registration flow, add email verification — it's your code.
238
+
239
+ > **Note:** The existing `/auth/login` and `/auth/register` routes are **not modified**. Each custom entity gets its own namespace (`/auth/<entity>/...`), so nothing breaks.
240
+
241
+ ---
242
+
190
243
  ## Environment variables
191
244
 
192
245
  | Variable | Wired into (via `efc.config.ts`) | Description |
@@ -196,3 +249,26 @@ and pass it through as `cookieDomain: process.env.COOKIE_DOMAIN` in `efc.config.
196
249
  | `COOKIE_DOMAIN` | `cookieDomain` | Cookie domain for `http-only` strategy |
197
250
 
198
251
  `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.
252
+
253
+ ---
254
+
255
+ ## Passwords
256
+
257
+ `express-file-cluster/auth` hashes passwords with scrypt from `node:crypto` — no `bcrypt`, no native
258
+ build step, nothing extra to install.
259
+
260
+ ```ts
261
+ import { hashPassword, verifyPassword, passwordNeedsRehash } from 'express-file-cluster/auth';
262
+
263
+ const passwordHash = await hashPassword(req.body.password); // on register / reset
264
+ const ok = await verifyPassword(req.body.password, user.passwordHash); // on login
265
+ if (ok && passwordNeedsRehash(user.passwordHash)) {
266
+ await User.update(user.id, { passwordHash: await hashPassword(req.body.password) });
267
+ }
268
+ ```
269
+
270
+ Hashes look like `scrypt$32768$8$1$<salt>$<key>`; the cost parameters are stored in each hash, so a
271
+ future default doesn't lock anyone out. Apps scaffolded before 0.9.2 stored **bcrypt** hashes, which
272
+ `verifyPassword` deliberately rejects (EFC carries no bcrypt code or dependency): those users reset
273
+ their password once — the reset route stores a scrypt hash. See the
274
+ [auth API reference](../api-reference/auth.md#hashpassword--verifypassword--passwordneedsrehash).
@@ -0,0 +1,60 @@
1
+ # Coming from mongoose
2
+
3
+ `defineCollection` keeps mongoose's query language, with the schema as a plain object, types inferred from it, and validation errors that become HTTP responses. Underneath it is still mongoose, so your data and indexes stay as they are.
4
+
5
+ ---
6
+
7
+ ## 1. Schemas
8
+
9
+ ```ts
10
+ // mongoose
11
+ const PlaceSchema = new Schema({
12
+ name: { type: String, required: true },
13
+ price: Schema.Types.Decimal128,
14
+ location: { type: { type: String, enum: ['Point'] }, coordinates: [Number] },
15
+ owner: { type: Schema.Types.ObjectId, ref: 'User' },
16
+ }, { timestamps: true });
17
+ PlaceSchema.index({ location: '2dsphere' });
18
+ export const Place = model('Place', PlaceSchema);
19
+
20
+ // EFC
21
+ export const Place = defineCollection('Place', {
22
+ name: { type: 'string', required: true },
23
+ price: { type: 'decimal128' },
24
+ location: { type: 'geoPoint', index: '2dsphere' },
25
+ owner: { type: 'objectId', ref: 'User' },
26
+ });
27
+ export type Place = InferRecord<typeof Place>; // no interface to keep in step
28
+ ```
29
+
30
+ | mongoose | EFC |
31
+ |---|---|
32
+ | `String`, `Number`, `Boolean`, `Date`, `ObjectId` | `'string'`, `'number'`, `'boolean'`, `'date'`, `'objectId'` |
33
+ | `Decimal128`, `BigInt`, `Buffer` | `'decimal128'` (string), `'long'` (bigint), `'binary'` (Buffer) |
34
+ | GeoJSON point sub-schema | `'geoPoint'` |
35
+ | `[String]`, `[SubSchema]` | `{ type: 'array', of: 'string' }`, `[{ … }]` |
36
+ | `required`, `default`, `enum`, `min`, `max`, `minlength`, `match`, `validate` | same names (`minLength`, `maxLength`) |
37
+ | `timestamps: true` | the default |
38
+ | `schema.index({...})` | `index:` on the field, or `options.indexes` |
39
+
40
+ ## 2. Queries
41
+
42
+ | mongoose | EFC |
43
+ |---|---|
44
+ | `Model.find(filter).select('name').sort('-createdAt').limit(10).lean()` | `Place.find(filter, { projection: { name: 1 }, sort: { createdAt: -1 }, limit: 10 })` |
45
+ | `.populate('owner')` | `{ populate: 'owner' }` |
46
+ | `findOne`, `findById`, `countDocuments`, `distinct`, `exists` | same names |
47
+ | `create`, `insertMany`, `updateOne`, `updateMany`, `replaceOne`, `deleteOne`, `deleteMany` | same names and result counts |
48
+ | `findOneAndUpdate(f, u, { new: true, upsert: true })` | `findOneAndUpdate(f, u, { returnDocument: 'after', upsert: true })` |
49
+ | `aggregate([...])`, `bulkWrite([...])`, `watch([...])` | same |
50
+ | `session` passed to every call | `transaction(async () => { … })` and calls inside join it |
51
+
52
+ Records are plain objects (like `lean()`) with a string `id`. Decimals come back as strings and longs as bigints.
53
+
54
+ ## 3. What you gain
55
+
56
+ - Validation errors become a **400** with `issues`, and duplicate keys a **409**, with no error-handling code.
57
+ - Collections and indexes are created on first use (`autoSync`), and `efc db generate` writes index migrations.
58
+ - Need one model for MongoDB and PostgreSQL? Use [`defineModel`](../api-reference/db.md) instead. See [Which model API?](./which-api.md).
59
+
60
+ Full reference: [`defineCollection`](../api-reference/collection.md).
@@ -1,24 +1,24 @@
1
1
  # Which model API?
2
2
 
3
- EFC has two ways to define a model. They share one foundation: the schema format, inferred types, validation, auto-sync, `transaction()`, undeclared-field rules and errors. They differ in which engines they run on and in their query vocabulary.
3
+ EFC has three ways to define a model. They share one foundation: the schema format, inferred types, validation, auto-sync, `transaction()`, undeclared-field rules and errors. They differ in which engines they run on and in their query vocabulary.
4
4
 
5
- | | `defineModel` | `defineTable` |
6
- |---|---|---|
7
- | Engine | MongoDB or PostgreSQL (set by `DATABASE_URL`) | PostgreSQL only |
8
- | Queries | mongoose-style: `find(filter, { sort, limit, populate })`, `$set`, `$inc` | Prisma-style: `findMany({ where, include, orderBy, take, cursor })`, `findUnique`, `upsert`, `groupBy`, `aggregate` |
9
- | Relations | `ref` + `populate` (a plain column on PostgreSQL) | real foreign keys, many-to-many join tables, `include` in one SQL statement, relation filters, nested writes |
10
- | Field types | the portable set (`string`, `number`, `boolean`, `date`, `objectId`, objects, arrays) | + `integer`, `bigint`, `decimal`, `uuid`, `json`, `varchar`, native arrays and enums, `serial` ids |
11
- | Migrations | auto-sync, `efc db generate` | auto-sync, `efc db generate`, `efc db pull`, `efc import-prisma` |
12
- | Wrong engine | — | fails at first use with an `[EFC]` error naming the model |
5
+ | | `defineModel` | `defineTable` | `defineCollection` |
6
+ |---|---|---|---|
7
+ | Engine | MongoDB or PostgreSQL (set by `DATABASE_URL`) | PostgreSQL only | MongoDB only |
8
+ | Queries | portable subset: `find(filter, { sort, limit, populate })`, `$set`, `$inc` | Prisma-style: `findMany({ where, include, orderBy, take, cursor })`, `findUnique`, `upsert`, `groupBy`, `aggregate` | mongoose-style: every query operator, `find(filter, { projection })`, `findOneAndUpdate`, `bulkWrite`, `aggregate(pipeline)`, `watch` |
9
+ | Relations | `ref` + `populate` (a plain column on PostgreSQL) | real foreign keys, many-to-many join tables, `include` in one SQL statement, relation filters, nested writes | `ref` + `populate`, `$lookup`, embedded documents |
10
+ | Field types | the portable set (`string`, `number`, `boolean`, `date`, `objectId`, objects, arrays) | + `integer`, `bigint`, `decimal`, `uuid`, `json`, `varchar`, native arrays and enums, `serial` ids | + `decimal128`, `long`, `geoPoint`, `binary`; `2dsphere`, `text`, `hashed` and partial indexes |
11
+ | Migrations | auto-sync, `efc db generate` | auto-sync, `efc db generate`, `efc db pull`, `efc import-prisma` | auto-sync, `efc db generate` |
12
+ | Wrong engine | — | fails at first use with an `[EFC]` error naming the model | the same |
13
13
 
14
14
  ## Pick one
15
15
 
16
16
  - **Building on PostgreSQL:** use `defineTable`. You get foreign keys, joins and SQL types. `create-efc-app` generates `defineTable` models for PostgreSQL apps.
17
- - **Building on MongoDB:** use `defineModel`. On MongoDB it *is* mongoose underneath (`Model.raw()` hands you the mongoose model), with `aggregate()`, TTL indexes and transactions on a replica set.
17
+ - **Building on MongoDB:** use `defineCollection`. You get the full query language, geo and text search, BSON types, `bulkWrite` and change streams. It is mongoose underneath (`raw()` hands you the mongoose model).
18
18
  - **The app may switch engines, or ships to both:** use `defineModel` and stay inside the shared filter and update subset (`$eq $ne $gt $gte $lt $lte $in $nin $exists $regex $and $or`; `$set $unset $inc $push $pull`).
19
19
  - **Coming from Prisma:** use `defineTable`. `efc import-prisma` writes the models for you. See [Coming from Prisma](./coming-from-prisma.md).
20
20
 
21
- ## The same query, both ways
21
+ ## The same query, three ways
22
22
 
23
23
  ```ts
24
24
  // defineModel
@@ -36,10 +36,19 @@ const posts = await Post.findMany({
36
36
  include: { author: true },
37
37
  });
38
38
  await Post.update({ where: { id }, data: { views: { increment: 1 } } });
39
+
40
+ // defineCollection
41
+ const posts = await Post.find(
42
+ { status: 'published', views: { $gte: 100 } },
43
+ { sort: { createdAt: -1 }, limit: 20, populate: 'author', projection: { body: 0 } },
44
+ );
45
+ await Post.findByIdAndUpdate(id, { $inc: { views: 1 } });
39
46
  ```
40
47
 
41
48
  ## Moving between them
42
49
 
50
+ On MongoDB, `defineModel` and `defineCollection` over the same collection read and write the same documents. Only the method names and results differ (`updateMany` returns `{ modifiedCount, … }` instead of a number, for example).
51
+
43
52
  On PostgreSQL, a `defineModel` and a `defineTable` over the same table read and write the same records, so you can move one model at a time. Two things change on the way:
44
53
 
45
54
  - A `ref` becomes a real foreign key. The field's `type` must match the target's id (`uuid` for the default id, `integer` for `id: 'serial'`). Rows pointing at missing records don't block the deploy: the key is added `NOT VALID`, and validation is skipped with a warning naming the count.
@@ -47,4 +56,4 @@ On PostgreSQL, a `defineModel` and a `defineTable` over the same table read and
47
56
 
48
57
  Run `efc db sync --dry-run` before you switch to see exactly what will change.
49
58
 
50
- See also: [Database guide](./database.md) · [Relations](./relations.md) · [`defineModel` API](../api-reference/db.md) · [`defineTable` API](../api-reference/table.md)
59
+ See also: [Database guide](./database.md) · [Relations](./relations.md) · [`defineModel` API](../api-reference/db.md) · [`defineTable` API](../api-reference/table.md) · [`defineCollection` API](../api-reference/collection.md)
@@ -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.9.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.9.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
 
@@ -37,11 +37,13 @@
37
37
  | [Authentication](./guides/authentication.md) | JWT strategies, login/logout, `requireAuth` |
38
38
  | [RBAC](./guides/rbac.md) | Role-based route protection via the `requireAuth('role')` shorthand |
39
39
  | [Database](./guides/database.md) | `defineModel`, queries, transactions, MongoDB vs PostgreSQL |
40
- | [Which model API?](./guides/which-api.md) | `defineModel` vs `defineTable`, and moving between them |
40
+ | [Which model API?](./guides/which-api.md) | `defineModel` vs `defineTable` vs `defineCollection`, and moving between them |
41
41
  | [Relations](./guides/relations.md) | Foreign keys, many-to-many, `include`, relation filters, nested writes |
42
42
  | [defineTable](./api-reference/table.md) | PostgreSQL-native models: Prisma-style queries, SQL types, aggregation |
43
+ | [defineCollection](./api-reference/collection.md) | MongoDB-native models: mongoose-style queries, BSON types, geo, bulk writes, change streams |
43
44
  | [Migrations & Seeds](./guides/migrations.md) | `efc db generate / migrate / rollback / pull / seed / studio`, drift checks |
44
45
  | [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
46
+ | [Coming from mongoose](./guides/coming-from-mongoose.md) | `defineCollection` for mongoose users: schema and query mapping |
45
47
  | [Validation](./guides/validation.md) | Route `schema` exports with zod, valibot, arktype |
46
48
  | [Logging](./guides/logging.md) | pino, request IDs, `getLogger()` |
47
49
  | [Caching & Sessions](./guides/caching.md) | `cache`, `cacheResponse`, revoking JWT sessions |
@@ -37,8 +37,8 @@ Load **only** the module the work points to. Each is self-contained.
37
37
  docs/ ← full documentation
38
38
  ```
39
39
 
40
- ## Status (v0.9.0 — Beta, Phase 2 complete + defineTable with relations + generated migrations + `efc add` registry)
40
+ ## Status (v0.9.2 — Beta, Phase 2 complete + defineTable with relations + generated migrations + `efc add` registry)
41
41
 
42
- Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only + localStorage auth, 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), 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.
42
+ Implemented: file-based router (incl. `[[id]]`, `[...slug]`, `[[...slug]]`), request validation (`export const schema`, Standard Schema), multi-core clustering with graceful shutdown, http-only + localStorage 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
- **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`, `defineCollection`.
44
+ **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`.
@@ -35,6 +35,14 @@ function defineModel(name: string, schema: ModelSchema, options?: ModelOptions):
35
35
  type InferRecord<typeof Model> // record incl. id + timestamps per options (defineModel and defineTable)
36
36
  type InferCreate<typeof Model> // create() input: required w/o default/sequence mandatory; dates accept string|number
37
37
  async function transaction<T>(fn: () => Promise<T>): Promise<T> // model calls inside join automatically
38
+ // MongoDB-native (mongoose vocabulary + BSON types); PostgreSQL → [EFC] error at first use
39
+ function defineCollection(name: string, schema: CollectionSchema, options?: CollectionOptions): CollectionModel<S, O>
40
+ // types: + 'decimal128' (string) 'long' (bigint) 'geoPoint' ({ type: 'Point', coordinates: [lng, lat] }) 'binary' (Buffer)
41
+ // index: true | '2dsphere' | 'text' | 'hashed'; options.indexes + partialFilterExpression; options.collation
42
+ // find(filter, { projection, sort, skip, limit, populate, collation }) · findOne · findById · exists · countDocuments · distinct
43
+ // create · insertMany · updateOne/updateMany/replaceOne(f, u, { upsert }) → { matchedCount, modifiedCount, upsertedCount, upsertedId }
44
+ // findOneAndUpdate(f, u, { upsert, returnDocument: 'before' (default) | 'after' }) · findByIdAndUpdate · findOneAndDelete · findByIdAndDelete
45
+ // deleteOne/deleteMany → { deletedCount } · bulkWrite(ops) · aggregate<T>(pipeline) · watch(pipeline) (replica set; for await)
38
46
  // PostgreSQL-native (Prisma vocabulary + SQL types); MongoDB → [EFC] error at first use
39
47
  function defineTable(name: string, schema: TableSchema, options?: TableOptions): TableModel<S, O>
40
48
  // types: + 'integer' (number) 'bigint' (bigint) 'decimal' {precision, scale} (string, exact) 'uuid' 'json'
@@ -255,6 +263,14 @@ function configureAuth(config: { secret: string; strategy: AuthStrategy; expires
255
263
  // Returns undefined outside a request, or on a route that never ran requireAuth.
256
264
  // Also what powers the '$currentUser'/'$currentUser.<key>' defineModel default codes.
257
265
  function getCurrentUser(): Record<string, unknown> | undefined
266
+
267
+ // Password hashing — node:crypto scrypt (source: auth/password.ts), no bcrypt dependency.
268
+ // Format scrypt$N$r$p$salt$key (defaults N=2^15 r=8 p=1). verifyPassword is constant-time,
269
+ // false on malformed hashes. NO bcrypt support at all: $2a/$2b/$2y$ hashes → false + a
270
+ // logged warning (user resets password). Scaffolded routes use these.
271
+ async function hashPassword(password: string): Promise<string>
272
+ async function verifyPassword(password: string, hash: string): Promise<boolean>
273
+ function passwordNeedsRehash(hash: string): boolean
258
274
  ```
259
275
 
260
276
  Cookie name: `efc_token`. Algorithm: HS256. Library: `jose`.
@@ -36,7 +36,8 @@ defineMiddleware()
36
36
  defineModel() // ← WAIT — this DOES exist, from main path
37
37
  createModel() // ← does NOT exist (it's defineModel, not createModel)
38
38
  defineTable() // ← EXISTS (PostgreSQL-only, Prisma-style) — see api-surface.md
39
- defineCollection() // ← NOT YET — planned (MongoDB-native API, prisma-parity-plan M5)
39
+ defineCollection() // ← EXISTS (MongoDB-only, mongoose vocabulary) — see api-surface.md
40
+ Collection.findMany() / include // ← defineTable vocabulary, NOT on defineCollection
40
41
  Model.findMany() / findUnique() / groupBy() // ← only on defineTable, NOT on defineModel
41
42
  Table.find() / findById() / $gt / $inc // ← defineModel vocabulary, NOT on defineTable
42
43
  Table.findMany({ include }) // ← EXISTS; so do relation filters `{ posts: { some } }` and nested writes `{ connect }` (defineTable only)
@@ -140,7 +141,7 @@ efc remove <item> # NOT IMPLEMENTED — `efc add` copies files; delete them yo
140
141
  efc add <url|@ns/x> # NOT IMPLEMENTED — only the built-in registry (efc list); no third-party registries
141
142
  ```
142
143
 
143
- `efc add | list | view | diff | init` DO exist (the feature registry, `docs/cli/add.md`).
144
+ `efc add | list | view | diff | init` DO exist (the feature registry, `docs/cli/add.md`). Custom auth entities can be scaffolded via `efc add auth --entity <name>`, `efc add auth:<name>`, or `efc add auth new <name>` (e.g. `efc add auth:merchant`).
144
145
  OAuth sign-in exists only as registry items (`efc add auth@google`, `efc add auth@apple`) —
145
146
  app code in `src/api/auth/<provider>/` + `src/lib/oauth`; there is NO framework OAuth API
146
147
  (no `passport`, no `oauth` option on `ignite()`, no other providers).