express-file-cluster 0.7.1 → 0.8.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 (193) hide show
  1. package/README.md +3 -1
  2. package/dist/auth/index.d.cts +1 -1
  3. package/dist/auth/index.d.ts +1 -1
  4. package/dist/chunk-75O3WQKR.cjs +1386 -0
  5. package/dist/chunk-75O3WQKR.cjs.map +1 -0
  6. package/dist/{chunk-6OGOVV57.js → chunk-B2I7SYQ3.js} +100 -1261
  7. package/dist/chunk-B2I7SYQ3.js.map +1 -0
  8. package/dist/chunk-BBSZLGZW.js +113 -0
  9. package/dist/chunk-BBSZLGZW.js.map +1 -0
  10. package/dist/{chunk-AZYXQU3Z.cjs → chunk-FQFKHPLR.cjs} +217 -1378
  11. package/dist/chunk-FQFKHPLR.cjs.map +1 -0
  12. package/dist/chunk-OSES7ZQ5.js +1386 -0
  13. package/dist/chunk-OSES7ZQ5.js.map +1 -0
  14. package/dist/chunk-QL6EWT4B.cjs +113 -0
  15. package/dist/chunk-QL6EWT4B.cjs.map +1 -0
  16. package/dist/cli/db-runner.cjs +611 -26
  17. package/dist/cli/db-runner.cjs.map +1 -1
  18. package/dist/cli/db-runner.js +610 -25
  19. package/dist/cli/db-runner.js.map +1 -1
  20. package/dist/cli/index.cjs +1210 -12
  21. package/dist/cli/index.cjs.map +1 -1
  22. package/dist/cli/index.js +1221 -23
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/docs/api-reference/db.md +1 -0
  25. package/dist/docs/cli/add.md +136 -0
  26. package/dist/docs/cli/db.md +25 -2
  27. package/dist/docs/cli/index.md +10 -1
  28. package/dist/docs/core-concepts/middleware.md +1 -1
  29. package/dist/docs/getting-started/index.md +25 -18
  30. package/dist/docs/getting-started/project-structure.md +6 -7
  31. package/dist/docs/guides/authentication.md +3 -1
  32. package/dist/docs/guides/coming-from-prisma.md +75 -0
  33. package/dist/docs/guides/database.md +3 -2
  34. package/dist/docs/guides/generated-portals.md +36 -19
  35. package/dist/docs/guides/mailer.md +7 -10
  36. package/dist/docs/guides/migrations.md +114 -3
  37. package/dist/docs/guides/oauth.md +94 -0
  38. package/dist/docs/guides/rbac.md +5 -40
  39. package/dist/docs/index.md +5 -3
  40. package/dist/docs/skills/SKILL.md +3 -3
  41. package/dist/docs/skills/what-not-to-invent.md +22 -6
  42. package/dist/index.cjs +10 -8
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.cts +2 -2
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.js +8 -6
  47. package/dist/index.js.map +1 -1
  48. package/dist/registry/index.json +506 -0
  49. package/dist/registry/js-mongo/_base.json +1 -0
  50. package/dist/registry/js-mongo/account-security.json +1 -0
  51. package/dist/registry/js-mongo/account-settings.json +1 -0
  52. package/dist/registry/js-mongo/admin-admins.json +1 -0
  53. package/dist/registry/js-mongo/admin-analytics.json +1 -0
  54. package/dist/registry/js-mongo/admin-billing.json +1 -0
  55. package/dist/registry/js-mongo/admin-content.json +1 -0
  56. package/dist/registry/js-mongo/admin-logs.json +1 -0
  57. package/dist/registry/js-mongo/admin-support.json +1 -0
  58. package/dist/registry/js-mongo/admin-system.json +1 -0
  59. package/dist/registry/js-mongo/admin-users.json +1 -0
  60. package/dist/registry/js-mongo/admin.json +1 -0
  61. package/dist/registry/js-mongo/auth.json +1 -0
  62. package/dist/registry/js-mongo/auth@apple.json +1 -0
  63. package/dist/registry/js-mongo/auth@google.json +1 -0
  64. package/dist/registry/js-mongo/billing.json +1 -0
  65. package/dist/registry/js-mongo/email-client.json +1 -0
  66. package/dist/registry/js-mongo/email-verification.json +1 -0
  67. package/dist/registry/js-mongo/files.json +1 -0
  68. package/dist/registry/js-mongo/forgot-password.json +1 -0
  69. package/dist/registry/js-mongo/notifications.json +1 -0
  70. package/dist/registry/js-mongo/support.json +1 -0
  71. package/dist/registry/js-mongo/user-profile.json +1 -0
  72. package/dist/registry/js-pg-model/_base.json +1 -0
  73. package/dist/registry/js-pg-model/account-security.json +1 -0
  74. package/dist/registry/js-pg-model/account-settings.json +1 -0
  75. package/dist/registry/js-pg-model/admin-admins.json +1 -0
  76. package/dist/registry/js-pg-model/admin-analytics.json +1 -0
  77. package/dist/registry/js-pg-model/admin-billing.json +1 -0
  78. package/dist/registry/js-pg-model/admin-content.json +1 -0
  79. package/dist/registry/js-pg-model/admin-logs.json +1 -0
  80. package/dist/registry/js-pg-model/admin-support.json +1 -0
  81. package/dist/registry/js-pg-model/admin-system.json +1 -0
  82. package/dist/registry/js-pg-model/admin-users.json +1 -0
  83. package/dist/registry/js-pg-model/admin.json +1 -0
  84. package/dist/registry/js-pg-model/auth.json +1 -0
  85. package/dist/registry/js-pg-model/auth@apple.json +1 -0
  86. package/dist/registry/js-pg-model/auth@google.json +1 -0
  87. package/dist/registry/js-pg-model/billing.json +1 -0
  88. package/dist/registry/js-pg-model/email-client.json +1 -0
  89. package/dist/registry/js-pg-model/email-verification.json +1 -0
  90. package/dist/registry/js-pg-model/files.json +1 -0
  91. package/dist/registry/js-pg-model/forgot-password.json +1 -0
  92. package/dist/registry/js-pg-model/notifications.json +1 -0
  93. package/dist/registry/js-pg-model/support.json +1 -0
  94. package/dist/registry/js-pg-model/user-profile.json +1 -0
  95. package/dist/registry/js-pg-table/_base.json +1 -0
  96. package/dist/registry/js-pg-table/account-security.json +1 -0
  97. package/dist/registry/js-pg-table/account-settings.json +1 -0
  98. package/dist/registry/js-pg-table/admin-admins.json +1 -0
  99. package/dist/registry/js-pg-table/admin-analytics.json +1 -0
  100. package/dist/registry/js-pg-table/admin-billing.json +1 -0
  101. package/dist/registry/js-pg-table/admin-content.json +1 -0
  102. package/dist/registry/js-pg-table/admin-logs.json +1 -0
  103. package/dist/registry/js-pg-table/admin-support.json +1 -0
  104. package/dist/registry/js-pg-table/admin-system.json +1 -0
  105. package/dist/registry/js-pg-table/admin-users.json +1 -0
  106. package/dist/registry/js-pg-table/admin.json +1 -0
  107. package/dist/registry/js-pg-table/auth.json +1 -0
  108. package/dist/registry/js-pg-table/auth@apple.json +1 -0
  109. package/dist/registry/js-pg-table/auth@google.json +1 -0
  110. package/dist/registry/js-pg-table/billing.json +1 -0
  111. package/dist/registry/js-pg-table/email-client.json +1 -0
  112. package/dist/registry/js-pg-table/email-verification.json +1 -0
  113. package/dist/registry/js-pg-table/files.json +1 -0
  114. package/dist/registry/js-pg-table/forgot-password.json +1 -0
  115. package/dist/registry/js-pg-table/notifications.json +1 -0
  116. package/dist/registry/js-pg-table/support.json +1 -0
  117. package/dist/registry/js-pg-table/user-profile.json +1 -0
  118. package/dist/registry/ts-mongo/_base.json +1 -0
  119. package/dist/registry/ts-mongo/account-security.json +1 -0
  120. package/dist/registry/ts-mongo/account-settings.json +1 -0
  121. package/dist/registry/ts-mongo/admin-admins.json +1 -0
  122. package/dist/registry/ts-mongo/admin-analytics.json +1 -0
  123. package/dist/registry/ts-mongo/admin-billing.json +1 -0
  124. package/dist/registry/ts-mongo/admin-content.json +1 -0
  125. package/dist/registry/ts-mongo/admin-logs.json +1 -0
  126. package/dist/registry/ts-mongo/admin-support.json +1 -0
  127. package/dist/registry/ts-mongo/admin-system.json +1 -0
  128. package/dist/registry/ts-mongo/admin-users.json +1 -0
  129. package/dist/registry/ts-mongo/admin.json +1 -0
  130. package/dist/registry/ts-mongo/auth.json +1 -0
  131. package/dist/registry/ts-mongo/auth@apple.json +1 -0
  132. package/dist/registry/ts-mongo/auth@google.json +1 -0
  133. package/dist/registry/ts-mongo/billing.json +1 -0
  134. package/dist/registry/ts-mongo/email-client.json +1 -0
  135. package/dist/registry/ts-mongo/email-verification.json +1 -0
  136. package/dist/registry/ts-mongo/files.json +1 -0
  137. package/dist/registry/ts-mongo/forgot-password.json +1 -0
  138. package/dist/registry/ts-mongo/notifications.json +1 -0
  139. package/dist/registry/ts-mongo/support.json +1 -0
  140. package/dist/registry/ts-mongo/user-profile.json +1 -0
  141. package/dist/registry/ts-pg-model/_base.json +1 -0
  142. package/dist/registry/ts-pg-model/account-security.json +1 -0
  143. package/dist/registry/ts-pg-model/account-settings.json +1 -0
  144. package/dist/registry/ts-pg-model/admin-admins.json +1 -0
  145. package/dist/registry/ts-pg-model/admin-analytics.json +1 -0
  146. package/dist/registry/ts-pg-model/admin-billing.json +1 -0
  147. package/dist/registry/ts-pg-model/admin-content.json +1 -0
  148. package/dist/registry/ts-pg-model/admin-logs.json +1 -0
  149. package/dist/registry/ts-pg-model/admin-support.json +1 -0
  150. package/dist/registry/ts-pg-model/admin-system.json +1 -0
  151. package/dist/registry/ts-pg-model/admin-users.json +1 -0
  152. package/dist/registry/ts-pg-model/admin.json +1 -0
  153. package/dist/registry/ts-pg-model/auth.json +1 -0
  154. package/dist/registry/ts-pg-model/auth@apple.json +1 -0
  155. package/dist/registry/ts-pg-model/auth@google.json +1 -0
  156. package/dist/registry/ts-pg-model/billing.json +1 -0
  157. package/dist/registry/ts-pg-model/email-client.json +1 -0
  158. package/dist/registry/ts-pg-model/email-verification.json +1 -0
  159. package/dist/registry/ts-pg-model/files.json +1 -0
  160. package/dist/registry/ts-pg-model/forgot-password.json +1 -0
  161. package/dist/registry/ts-pg-model/notifications.json +1 -0
  162. package/dist/registry/ts-pg-model/support.json +1 -0
  163. package/dist/registry/ts-pg-model/user-profile.json +1 -0
  164. package/dist/registry/ts-pg-table/_base.json +1 -0
  165. package/dist/registry/ts-pg-table/account-security.json +1 -0
  166. package/dist/registry/ts-pg-table/account-settings.json +1 -0
  167. package/dist/registry/ts-pg-table/admin-admins.json +1 -0
  168. package/dist/registry/ts-pg-table/admin-analytics.json +1 -0
  169. package/dist/registry/ts-pg-table/admin-billing.json +1 -0
  170. package/dist/registry/ts-pg-table/admin-content.json +1 -0
  171. package/dist/registry/ts-pg-table/admin-logs.json +1 -0
  172. package/dist/registry/ts-pg-table/admin-support.json +1 -0
  173. package/dist/registry/ts-pg-table/admin-system.json +1 -0
  174. package/dist/registry/ts-pg-table/admin-users.json +1 -0
  175. package/dist/registry/ts-pg-table/admin.json +1 -0
  176. package/dist/registry/ts-pg-table/auth.json +1 -0
  177. package/dist/registry/ts-pg-table/auth@apple.json +1 -0
  178. package/dist/registry/ts-pg-table/auth@google.json +1 -0
  179. package/dist/registry/ts-pg-table/billing.json +1 -0
  180. package/dist/registry/ts-pg-table/email-client.json +1 -0
  181. package/dist/registry/ts-pg-table/email-verification.json +1 -0
  182. package/dist/registry/ts-pg-table/files.json +1 -0
  183. package/dist/registry/ts-pg-table/forgot-password.json +1 -0
  184. package/dist/registry/ts-pg-table/notifications.json +1 -0
  185. package/dist/registry/ts-pg-table/support.json +1 -0
  186. package/dist/registry/ts-pg-table/user-profile.json +1 -0
  187. package/dist/tasks/index.d.cts +1 -1
  188. package/dist/tasks/index.d.ts +1 -1
  189. package/dist/{types-B6lVw4bj.d.cts → types-B1tJoI4g.d.cts} +6 -0
  190. package/dist/{types-B6lVw4bj.d.ts → types-B1tJoI4g.d.ts} +6 -0
  191. package/package.json +11 -2
  192. package/dist/chunk-6OGOVV57.js.map +0 -1
  193. package/dist/chunk-AZYXQU3Z.cjs.map +0 -1
@@ -4,17 +4,128 @@
4
4
 
5
5
  | Command | Does |
6
6
  |---|---|
7
+ | `efc db generate <name>` | Writes a migration from the difference between your models and your migrations |
7
8
  | `efc db migrate` | Runs pending migrations in `src/migrations/` as one new batch |
8
9
  | `efc db rollback [--steps n]` | Reverts the last batch (or `n` batches), newest first |
9
10
  | `efc db status` | Lists applied (with batch) and pending migrations |
10
11
  | `efc db seed [name]` | Runs every seed in `src/seeds/`, or just one |
12
+ | `efc db sync [--dry-run] [--exit-code]` | Brings the database in line with the models (or reports what would change) |
13
+ | `efc db pull` | Writes `defineTable` models for an existing PostgreSQL database |
11
14
  | `efc db studio [-p 4983]` | Opens a read-only database browser on `127.0.0.1` |
12
15
 
13
16
  All of them read `DATABASE_URL` from the environment or `.env` (override with `--database-url`); the engine follows the URL scheme.
14
17
 
15
18
  ---
16
19
 
17
- ## Writing a migration
20
+ ## Generating a migration from your models
21
+
22
+ Change a model, then let EFC write the migration:
23
+
24
+ ```bash
25
+ efc db generate add_post_views
26
+ # → src/migrations/20261023101500_add_post_views.ts
27
+ ```
28
+
29
+ `generate` replays your existing migrations into a **throwaway schema** (PostgreSQL) or database (MongoDB) on the same server, compares the result with the models in `src/model(s)/`, and writes the difference. Your development database isn't read or changed, so it doesn't matter that `autoSync` already brought it up to date. Run it without a name to just print the plan.
30
+
31
+ The file is ordinary code you own and should review:
32
+
33
+ ```ts
34
+ // Generated by `efc db generate add_post_views` on 2026-10-23. Review it, then run `efc db migrate`.
35
+ import type { MigrationContext } from 'express-file-cluster';
36
+
37
+ export async function up({ db }: MigrationContext): Promise<void> {
38
+ await run(db, [
39
+ `ALTER TABLE "posts" ADD COLUMN IF NOT EXISTS "views" integer`,
40
+ `CREATE INDEX IF NOT EXISTS "posts_views_idx" ON "posts" ("views")`,
41
+ ]);
42
+ }
43
+
44
+ export async function down({ db }: MigrationContext): Promise<void> {
45
+ await run(db, [
46
+ `DROP INDEX IF EXISTS "posts_views_idx"`,
47
+ `ALTER TABLE "posts" DROP COLUMN IF EXISTS "views"`,
48
+ ]);
49
+ }
50
+ // …plus a small run() helper: one transaction, checks, and skip-if-applied guards
51
+ ```
52
+
53
+ - **PostgreSQL:** the steps are SQL run in one transaction. Tables come first and foreign keys last, so models can reference each other in any order. Every statement is idempotent (`IF NOT EXISTS`, or guarded by a "skip if already applied" query), so running a migration over tables that already exist changes nothing.
54
+ - **MongoDB:** the steps create collections, build and drop indexes, and move renamed fields in stored documents.
55
+ - **`down()`** is a best-effort reverse. Anything without a safe inverse (a dropped column's data, an added enum value) is listed in a comment.
56
+
57
+ ### What `generate` adds, and what it needs you to ask for
58
+
59
+ By default a migration contains what `sync` would do: create tables, columns, indexes, enum types and foreign keys, convert changed types, and relax `NOT NULL`s the model no longer asks for. Two kinds of change go further and need a flag:
60
+
61
+ | You want | Do | The migration |
62
+ |---|---|---|
63
+ | Rename a field and keep its data | `headline: { type: 'string', renamedFrom: 'title' }` | PostgreSQL: `RENAME COLUMN` (`sync` does this too). MongoDB: `$rename` in the stored documents |
64
+ | Drop columns the model no longer declares | `efc db generate <name> --allow-drop` | `DROP COLUMN` (the data is gone; `down()` re-adds an empty column) |
65
+ | Enforce `required` and `enum` in the database | `efc db generate <name> --tighten` | `SET NOT NULL` for required fields, `VALIDATE` for enum checks |
66
+
67
+ Tightening can fail on existing rows, so each step comes with a check that runs first. If anything would fail, the migration stops before changing anything, says how many rows are affected and what to fix, and the next `migrate` retries:
68
+
69
+ ```
70
+ GenPost.headline is required, but 3 row(s) of "posts" have no value — fill them in, then run the migration again
71
+ ```
72
+
73
+ Foreign keys are validated in the migration the same way, after a count of rows that reference a missing record.
74
+
75
+ ### Checking migrations against the models
76
+
77
+ ```bash
78
+ efc db generate --verify
79
+ ```
80
+
81
+ `--verify` replays every migration into a throwaway schema and fails (exit code 1) if the result is missing anything the models declare, listing the steps. Use it in CI so a model change can't ship without its migration. With a name, `generate <name> --verify` writes the migration and then verifies it.
82
+
83
+ ### Drift: does the live database match?
84
+
85
+ ```bash
86
+ efc db sync --dry-run --exit-code
87
+ ```
88
+
89
+ This exits with code 2 when the database differs from the models (and 1 on an error). Run it against staging or production before a deploy.
90
+
91
+ ### Starting migrations on an existing database
92
+
93
+ An app that has run on `autoSync` already has its tables. To start tracking migrations:
94
+
95
+ ```bash
96
+ efc db generate init # the whole current schema
97
+ efc db migrate --baseline # record it as applied, without running it
98
+ ```
99
+
100
+ `--baseline` records every pending migration as applied without running it. Because generated migrations are idempotent, running `init` instead also works: it skips what exists.
101
+
102
+ ---
103
+
104
+ ## Pulling an existing database (PostgreSQL)
105
+
106
+ ```bash
107
+ efc db pull # → src/model/<Model>.ts + index.ts
108
+ efc db pull --out pulled # somewhere else, to compare
109
+ ```
110
+
111
+ `pull` reads the current schema and writes `defineTable` models. It carries over:
112
+
113
+ - **Tables and ids:** each table with a single `id` primary key (uuid, integer or bigint) becomes a model. Integer and bigint ids become `id: 'serial'` and `'bigserial'`.
114
+ - **Columns and types:** varchar lengths, numeric precision, arrays and native enums. `NOT NULL` becomes `required: true`.
115
+ - **Defaults:** `now()`, `gen_random_uuid()`, literals and EFC sequences.
116
+ - **Naming:** `naming: 'snake_case'` when the columns follow it, plus `column` overrides and the table name.
117
+ - **Indexes:** unique, plain, compound and text indexes.
118
+ - **Relations:** foreign keys become `ref`s with `onDelete`. A column like `authorId` becomes an `author` field that keeps the `authorId` column. EFC join tables become many-to-many arrays, and every target model gets back-`relations`.
119
+
120
+ A schema EFC created pulls back to models that sync finds nothing to change in. For a schema EFC didn't create, anything that has no EFC equivalent is noted at the top of the file: expression or partial indexes, other CHECKs, composite keys, and other defaults. Existing files are kept unless you pass `--force`.
121
+
122
+ `required` and `default` live in the model, not the database. A table created by `sync` or a migration without `--tighten` has nullable columns and no defaults, so its fields pull back as optional. Generate with `--tighten` if you want `required` enforced (and pulled back).
123
+
124
+ Coming from Prisma? See [Coming from Prisma](./coming-from-prisma.md).
125
+
126
+ ---
127
+
128
+ ## Writing a migration by hand
18
129
 
19
130
  ```bash
20
131
  efc generate migration add_orders
@@ -39,7 +150,7 @@ export async function down({ db, engine }: MigrationContext): Promise<void> {
39
150
  - `Model.sync()` reconciles the table/collection with the model (see [the schema takes care of itself](./database.md#the-schema-takes-care-of-itself)). It never drops a column or data, so it's safe to call from several migrations.
40
151
  - `Model.drop()` removes the table/collection — for `down()`.
41
152
 
42
- **Do I need migrations at all?** Not for schema shape: tables and indexes are reconciled automatically on first use. Use migrations for what sync deliberately won't do — renaming or splitting columns, backfilling data, dropping columns — and, if you run with `autoSync: false`, for every schema change. Projects created with `create-efc-app` include `src/migrations/00000000000000_init`, which syncs every generated model; running it is optional.
153
+ **Do I need migrations at all?** Not for schema shape: tables and indexes are reconciled automatically on first use. Use migrations for what sync deliberately won't do, such as dropping columns, enforcing `NOT NULL`, splitting columns or backfilling data. If you run with `autoSync: false`, you need them for every schema change. `efc db generate` writes most of them for you. Projects created with `create-efc-app` include `src/migrations/00000000000000_init`, which syncs every generated model. Running it is optional. While `generate` replays migrations into its throwaway schema, `Model.sync()` calls inside them do nothing, because they'd mirror today's models and hide every change. So the first `efc db generate` in such an app captures the whole schema, and running it against your existing tables is harmless.
43
154
 
44
155
  ### `efc db sync`
45
156
 
@@ -48,7 +159,7 @@ efc db sync --dry-run # every model in src/model(s)/: what would change (SQL o
48
159
  efc db sync # apply
49
160
  ```
50
161
 
51
- Handy in CI (fail if `--dry-run` reports pending changes) and as the deploy step when `autoSync` is off.
162
+ Handy as the deploy step when `autoSync` is off. In CI, `--dry-run --exit-code` exits with code 2 when anything would change.
52
163
 
53
164
  ---
54
165
 
@@ -0,0 +1,94 @@
1
+ # Sign in with Google & Apple
2
+
3
+ Two registry items add OAuth sign-in next to email/password [auth](./authentication.md):
4
+
5
+ ```bash
6
+ efc add auth@google # asks for the Google client ID and secret
7
+ efc add auth@apple # asks for the Services ID, Team ID, Key ID and .p8 key
8
+ ```
9
+
10
+ Both install `auth` first if it's missing. Like every [registry item](../cli/add.md), the code is copied into your app and is yours to change. Nothing about it is hidden in a package.
11
+
12
+ ---
13
+
14
+ ## What gets added
15
+
16
+ | File | Purpose |
17
+ |---|---|
18
+ | `src/api/auth/google/index.ts` | `GET /auth/google`: redirects to Google's consent screen |
19
+ | `src/api/auth/google/callback.ts` | `GET /auth/google/callback`: Google redirects here, the user is signed in |
20
+ | `src/api/auth/apple/index.ts` | `GET /auth/apple`: redirects to Apple |
21
+ | `src/api/auth/apple/callback.ts` | `POST /auth/apple/callback`: Apple posts here (`form_post`), the user is signed in |
22
+ | `src/lib/oauth.ts` | Shared: the state cookie, find-or-create the user, issue the token |
23
+ | `src/model/OAuthAccount.ts` | Links a provider identity (`google:<sub>`) to a `User` |
24
+
25
+ Plus the `jose` package, which verifies the providers' ID tokens and signs Apple's client secret, and these env vars:
26
+
27
+ | Variable | |
28
+ |---|---|
29
+ | `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | From your OAuth client in the Google Cloud console |
30
+ | `GOOGLE_REDIRECT_URI` | The callback URL, e.g. `http://localhost:3000/v1/api/auth/google/callback`. Register exactly this URL on the client |
31
+ | `APPLE_CLIENT_ID` | Your Services ID, e.g. `com.yourapp.signin` |
32
+ | `APPLE_TEAM_ID`, `APPLE_KEY_ID` | Your team ID and the ID of your Sign in with Apple key |
33
+ | `APPLE_PRIVATE_KEY` | The `.p8` key's contents, newlines written as `\n`. `efc add` reads the file for you |
34
+ | `APPLE_REDIRECT_URI` | The callback URL. It must be https, on a domain verified with Apple, and registered on the Services ID. Apple rejects `localhost` |
35
+ | `OAUTH_SUCCESS_REDIRECT` | Where the browser goes after signing in (your frontend) |
36
+
37
+ ---
38
+
39
+ ## Setting up the providers
40
+
41
+ **Google.** In [console.cloud.google.com](https://console.cloud.google.com), go to *APIs & Services → Credentials → Create credentials → OAuth client ID*. Choose application type *Web application* and add `GOOGLE_REDIRECT_URI` under *Authorised redirect URIs*. Configure the consent screen if asked; the `openid`, `email` and `profile` scopes are enough.
42
+
43
+ **Apple.** In [developer.apple.com](https://developer.apple.com) → *Certificates, IDs & Profiles*:
44
+
45
+ 1. An **App ID** with *Sign in with Apple* enabled.
46
+ 2. A **Services ID** (this is `APPLE_CLIENT_ID`) with *Sign in with Apple* enabled, your domain, and `APPLE_REDIRECT_URI` as a return URL.
47
+ 3. A **Key** with *Sign in with Apple*. Download the `.p8` file (you can only do this once) and note its Key ID.
48
+
49
+ To try Apple sign-in locally, expose your dev server over https with a tunnel and register that URL.
50
+
51
+ ---
52
+
53
+ ## Using it from a frontend
54
+
55
+ Send the browser (not `fetch`) to the start route:
56
+
57
+ ```html
58
+ <a href="https://api.yourapp.com/v1/api/auth/google">Continue with Google</a>
59
+ <a href="https://api.yourapp.com/v1/api/auth/apple">Continue with Apple</a>
60
+ ```
61
+
62
+ After the provider sends the user back, the callback sets the usual `efc_token` cookie (the same one `/auth/login` sets) and redirects to `OAUTH_SUCCESS_REDIRECT`. From there, requests with credentials work as after a password login, and `GET /auth/me` returns the user.
63
+
64
+ > The callbacks issue the session as an http-only cookie, so they fit `authStrategy: 'http-only'`. With the `localStorage` (Bearer) strategy, change the callback to hand the token to your SPA, for example with `signToken()` and a redirect to your frontend that carries it.
65
+
66
+ ---
67
+
68
+ ## How sign-in works
69
+
70
+ 1. **Start.** The start route stores a random `state` and `nonce` (and, for Google, a PKCE verifier) in a short-lived http-only cookie, then redirects to the provider.
71
+ 2. **Callback.** The callback checks `state` against the cookie and clears it. It trades the code for tokens at the provider (Google: with the PKCE verifier; Apple: with a client secret, an ES256 JWT signed with your key) and verifies the ID token's signature, issuer, audience and `nonce` against the provider's published keys.
72
+ 3. **Find or create the user** (`signInWithOAuth` in `src/lib/oauth.ts`):
73
+ - the `User` already linked to this identity in `OAuthAccount`; otherwise
74
+ - the `User` with the same email, **if the provider says the email is verified**, which then gets linked; otherwise
75
+ - a new `User` (`isVerified: true`, a random password; they can set a real one with [forgot-password](./generated-portals.md)).
76
+
77
+ An unknown identity without a verified email is refused (400). A suspended user (`isActive: false`) gets 403.
78
+ 4. **Sign in.** `issueToken()` sets the cookie and the browser goes to `OAUTH_SUCCESS_REDIRECT`.
79
+
80
+ Apple only sends the user's name on their **first** sign-in. The callback uses it when it creates the user.
81
+
82
+ Apple posts its callback from its own site, so the start route marks the Apple state cookie `SameSite=None; Secure`. Browsers accept that on https and on `localhost`.
83
+
84
+ ---
85
+
86
+ ## Errors
87
+
88
+ | Status | When |
89
+ |---|---|
90
+ | 400 | The provider returned an error, the state is missing, expired (10 minutes) or doesn't match, the `nonce` doesn't match, or there's no verified email for a new identity |
91
+ | 403 | The user is suspended |
92
+ | 502 | The provider rejected the code exchange (wrong client secret / key, code already used, redirect URI mismatch) |
93
+
94
+ The callbacks answer with JSON errors. To send users back to your frontend instead, catch the error in the callback and redirect, e.g. to `${OAUTH_SUCCESS_REDIRECT}?error=…`.
@@ -1,21 +1,6 @@
1
1
  # Role-Based Access Control (RBAC)
2
2
 
3
- Role checks are built into `requireAuth` itself — call it with role names (`requireAuth('admin')`) instead of a separate middleware (see [Authentication](./authentication.md)). `create-efc-app` can also scaffold a `Role` model and role-management API for you via the **RBAC** feature option.
4
-
5
- ---
6
-
7
- ## Enabling it
8
-
9
- Toggle **Role-based access control** in the features multiselect:
10
-
11
- ```
12
- ? Features: (space to toggle, enter to confirm)
13
- ◉ User portal
14
- ◉ Admin portal
15
- ◉ Role-based access control
16
- ```
17
-
18
- RBAC is most useful alongside **User portal** and/or **Admin portal**, since it changes how their generated routes are protected — but it can be toggled independently.
3
+ Role checks are built into `requireAuth` itself — call it with role names (`requireAuth('admin')`) instead of a separate middleware (see [Authentication](./authentication.md)). The routes the registry generates use it throughout, and the `admin-admins` item adds a `Role` model and a role-management API.
19
4
 
20
5
  ---
21
6
 
@@ -23,7 +8,7 @@ RBAC is most useful alongside **User portal** and/or **Admin portal**, since it
23
8
 
24
9
  ### Route protection
25
10
 
26
- Every generated route that would otherwise export `middlewares = [requireAuth]` instead exports:
11
+ Every protected route that [`efc add`](../cli/add.md) or `create-efc-app` generates checks roles with `requireAuth(...)`:
27
12
 
28
13
  ```ts
29
14
  // User-facing routes
@@ -33,31 +18,11 @@ export const middlewares = [requireAuth('user', 'admin')];
33
18
  export const middlewares = [requireAuth('admin')];
34
19
  ```
35
20
 
36
- `requireAuth('admin')` verifies the JWT *and* checks that `payload.role` is one of the given roles — returning `401` if the token is missing/invalid, `403` if the role doesn't match.
37
-
38
- If RBAC is **not** enabled, admin routes fall back to an inline guard at the top of the handler instead:
39
-
40
- ```ts
41
- export const middlewares = [requireAuth];
42
-
43
- export const GET = async (req, res) => {
44
- const user = (req as any).user;
45
- if (user?.role !== 'admin') {
46
- return res.status(403).json({ error: 'Forbidden: Admin access required' });
47
- }
48
- // ...
49
- };
50
- ```
51
-
52
- Both approaches produce the same 401/403 behavior — RBAC-on just centralizes the check into `requireAuth(...)` and adds the `Role` model below.
53
-
54
- ### `Role` model
55
-
56
- A `src/model/Role.ts` model is created (`defineModel` on MongoDB, `defineTable` on PostgreSQL by default).
21
+ `requireAuth('admin')` verifies the JWT *and* checks that `payload.role` is one of the given roles. It returns `401` if the token is missing or invalid, and `403` if the role doesn't match.
57
22
 
58
- ### Admin role management routes
23
+ ### `Role` model and role management
59
24
 
60
- If **RBAC** and **Admin portal** are both enabled, a full role-management API is scaffolded:
25
+ `efc add admin-admins` creates `src/model/Role.ts` (`defineModel` on MongoDB, `defineTable` on PostgreSQL by default) and a role-management API:
61
26
 
62
27
  | Method | Path |
63
28
  |---|---|
@@ -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.7.1 — 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, and migrations are all implemented.
5
+ > **Status: v0.8.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, 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
 
@@ -26,7 +26,7 @@
26
26
  | [Getting Started](./getting-started/index.md) | Scaffold a project, understand the structure |
27
27
  | [Core Concepts](./core-concepts/index.md) | The four pillars: routing, clustering, tasks, middleware |
28
28
  | [API Reference](./api-reference/ignite.md) | Every exported function and type, fully documented |
29
- | [Guides](./guides/authentication.md) | Deep-dives: auth, database, RBAC, mailer, error handling, deployment |
29
+ | [Guides](./guides/authentication.md) | Deep-dives: auth, OAuth, database, RBAC, mailer, error handling, deployment |
30
30
  | [CLI](./cli/index.md) | All `efc` commands with flags and examples |
31
31
  | [Contributing](./contributing/index.md) | Roadmap, branch conventions, PR requirements |
32
32
 
@@ -38,12 +38,14 @@
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
40
  | [defineTable](./api-reference/table.md) | PostgreSQL-native models: Prisma-style queries, SQL types, aggregation |
41
- | [Migrations & Seeds](./guides/migrations.md) | `efc db migrate / rollback / seed / studio` |
41
+ | [Migrations & Seeds](./guides/migrations.md) | `efc db generate / migrate / rollback / pull / seed / studio`, drift checks |
42
+ | [Coming from Prisma](./guides/coming-from-prisma.md) | `efc import-prisma`, schema and query mapping |
42
43
  | [Validation](./guides/validation.md) | Route `schema` exports with zod, valibot, arktype |
43
44
  | [Logging](./guides/logging.md) | pino, request IDs, `getLogger()` |
44
45
  | [Caching & Sessions](./guides/caching.md) | `cache`, `cacheResponse`, revoking JWT sessions |
45
46
  | [Generated Portals](./guides/generated-portals.md) | Every model and route `create-efc-app` scaffolds for the User/Admin portals |
46
47
  | [Mailer](./guides/mailer.md) | Gmail (app password) and custom SMTP setup, sending email from a task |
48
+ | [Sign in with Google & Apple](./guides/oauth.md) | `efc add auth@google` / `auth@apple`: setup, flow, account linking |
47
49
  | [Environment Variables](./guides/environment-variables.md) | Full `.env` reference |
48
50
  | [Error Handling](./guides/error-handling.md) | `HttpError`, custom handlers, task failures |
49
51
  | [Deployment](./guides/deployment.md) | Build, start, and ship to production |
@@ -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.7.1 — Beta, Phase 2 complete + defineTable with relations)
40
+ ## Status (v0.8.0 — Beta, Phase 2 complete + defineTable with relations + `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`), 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, 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.
43
43
 
44
- **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`, schema-diff migration generation.
44
+ **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`, `defineCollection`.
@@ -133,12 +133,24 @@ export default async function(req, res) { ... } // NOT called as a route handl
133
133
  ```bash
134
134
  efc lint # NOT IMPLEMENTED
135
135
  efc deploy # NOT IMPLEMENTED
136
- efc db generate # NOT IMPLEMENTED — no schema-diff migration generator; write migrations
137
- # by hand (efc generate migration <name>) and call Model.sync()
138
136
  efc db reset / fresh # NOT IMPLEMENTED
137
+ efc db push # NOT IMPLEMENTED — that's `efc db sync` (or autoSync)
138
+ efc db pull # PostgreSQL only — MongoDB is NOT supported (exits with an error)
139
+ efc remove <item> # NOT IMPLEMENTED — `efc add` copies files; delete them yourself
140
+ efc add <url|@ns/x> # NOT IMPLEMENTED — only the built-in registry (efc list); no third-party registries
139
141
  ```
140
142
 
141
- Implemented commands: `start dev|prod`, `build prod`, `run tests`, `generate route|task|middleware|migration|seed`, `db migrate|rollback|status|seed|studio`, `routes`, `tasks` (+ `failed|retry|purge`), `doctor`, `--version`.
143
+ `efc add | list | view | diff | init` DO exist (the feature registry, `docs/cli/add.md`).
144
+ OAuth sign-in exists only as registry items (`efc add auth@google`, `efc add auth@apple`) —
145
+ app code in `src/api/auth/<provider>/` + `src/lib/oauth`; there is NO framework OAuth API
146
+ (no `passport`, no `oauth` option on `ignite()`, no other providers).
147
+
148
+ Implemented commands: `start dev|prod`, `build prod`, `run tests`, `generate route|task|middleware|migration|seed`, `db generate|migrate|rollback|status|sync|pull|seed|studio`, `import-prisma`, `routes`, `tasks` (+ `failed|retry|purge`), `doctor`, `--version`.
149
+
150
+ `efc db generate [name] [--allow-drop] [--tighten] [--verify]` DOES exist: it replays the
151
+ migrations into a throwaway schema/database, diffs the models against it and writes
152
+ `src/migrations/<ts>_<name>.(ts|js)`. Flags: `efc db sync --dry-run --exit-code` (exit 2 on
153
+ drift), `efc db migrate --baseline` (record as applied without running).
142
154
 
143
155
  ---
144
156
 
@@ -150,9 +162,13 @@ Implemented commands: `start dev|prod`, `build prod`, `run tests`, `generate rou
150
162
  // ✅ Tables are created and reconciled automatically on first use (autoSync, default on):
151
163
  // add column, change type (with cast), drop stale NOT NULL, rebuild enum CHECK,
152
164
  // create/drop EFC-named indexes. `efc db sync --dry-run` prints the SQL.
153
- // ❌ Sync never DROPS or RENAMES columns and never deletes rows — renames, splits and
154
- // backfills need a hand-written migration (db.query()).
155
- // ❌ No `efc db generate` that writes migration files from model diffs.
165
+ // ✅ Sync RENAMES a column when the field declares `renamedFrom: 'oldName'` (PostgreSQL);
166
+ // on MongoDB `efc db generate` writes the `$rename` migration.
167
+ // ❌ Sync never DROPS columns, never adds NOT NULL and never deletes rows — that's
168
+ // `efc db generate <name> --allow-drop` / `--tighten` (explicit, reviewed migrations).
169
+ // Splits and backfills still need a hand-written migration (db.query()).
170
+ // ✅ `efc db generate` writes migrations from model diffs; `efc db pull` (PostgreSQL) and
171
+ // `efc import-prisma` write defineTable model files.
156
172
  // ❌ No joins in the model API — populate does a second query; for SQL joins use
157
173
  // Drizzle via Model.raw() or db.query().
158
174
  // ❌ aggregate() is MongoDB-only (rejects on PostgreSQL).
package/dist/index.cjs CHANGED
@@ -20,12 +20,14 @@ var _chunkT4OHFU5Tcjs = require('./chunk-T4OHFU5T.cjs');
20
20
 
21
21
 
22
22
 
23
+ var _chunkFQFKHPLRcjs = require('./chunk-FQFKHPLR.cjs');
23
24
 
24
25
 
25
26
 
26
27
 
27
28
 
28
- var _chunkAZYXQU3Zcjs = require('./chunk-AZYXQU3Z.cjs');
29
+
30
+ var _chunk75O3WQKRcjs = require('./chunk-75O3WQKR.cjs');
29
31
 
30
32
 
31
33
 
@@ -995,14 +997,14 @@ async function ignite(config) {
995
997
  for (const mw of globalMiddlewares) {
996
998
  app.use(mw);
997
999
  }
998
- if (database) _chunkAZYXQU3Zcjs.setDbEngine.call(void 0, database);
999
- _chunkAZYXQU3Zcjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
1000
+ if (database) _chunk75O3WQKRcjs.setDbEngine.call(void 0, database);
1001
+ _chunk75O3WQKRcjs.setAutoSync.call(void 0, _nullishCoalesce(config.autoSync, () => ( true)));
1000
1002
  if (database === "mongodb" && databaseUrl) {
1001
- const conn = await _chunkAZYXQU3Zcjs.connectMongo.call(void 0, databaseUrl);
1002
- _chunkAZYXQU3Zcjs.setDbClient.call(void 0, conn);
1003
+ const conn = await _chunkFQFKHPLRcjs.connectMongo.call(void 0, databaseUrl);
1004
+ _chunkFQFKHPLRcjs.setDbClient.call(void 0, conn);
1003
1005
  } else if (database === "postgresql" && databaseUrl) {
1004
1006
  const pool = await _chunkMGH4VDV3cjs.connectPostgres.call(void 0, databaseUrl);
1005
- _chunkAZYXQU3Zcjs.setDbClient.call(void 0, pool);
1007
+ _chunkFQFKHPLRcjs.setDbClient.call(void 0, pool);
1006
1008
  }
1007
1009
  if (config.cache) {
1008
1010
  await _chunkZDM5JHVKcjs.configureCache.call(void 0, config.cache);
@@ -1063,7 +1065,7 @@ async function ignite(config) {
1063
1065
  return;
1064
1066
  }
1065
1067
  const duckTyped = err instanceof Error && typeof err.statusCode === "number" ? err : null;
1066
- if (_chunkAZYXQU3Zcjs.isHttpError.call(void 0, err)) {
1068
+ if (_chunk75O3WQKRcjs.isHttpError.call(void 0, err)) {
1067
1069
  const issues = err.issues;
1068
1070
  res.status(err.statusCode).json({
1069
1071
  error: err.message,
@@ -1137,5 +1139,5 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1137
1139
 
1138
1140
 
1139
1141
 
1140
- exports.HttpError = _chunkAZYXQU3Zcjs.HttpError; exports.ModelValidationError = _chunkAZYXQU3Zcjs.ModelValidationError; exports.cache = _chunkZDM5JHVKcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkAZYXQU3Zcjs.db; exports.defineModel = _chunkAZYXQU3Zcjs.defineModel; exports.defineTable = _chunkAZYXQU3Zcjs.defineTable; exports.getDbClient = _chunkAZYXQU3Zcjs.getDbClient; exports.getLogger = _chunkYL37D6KMcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkAZYXQU3Zcjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkYL37D6KMcjs.logger; exports.scanDir = _chunkR34R7QPDcjs.scanDir; exports.setDbClient = _chunkAZYXQU3Zcjs.setDbClient; exports.transaction = _chunkAZYXQU3Zcjs.transaction; exports.workerCount = workerCount;
1142
+ exports.HttpError = _chunk75O3WQKRcjs.HttpError; exports.ModelValidationError = _chunk75O3WQKRcjs.ModelValidationError; exports.cache = _chunkZDM5JHVKcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkFQFKHPLRcjs.db; exports.defineModel = _chunkFQFKHPLRcjs.defineModel; exports.defineTable = _chunkFQFKHPLRcjs.defineTable; exports.getDbClient = _chunkFQFKHPLRcjs.getDbClient; exports.getLogger = _chunkYL37D6KMcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunk75O3WQKRcjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkYL37D6KMcjs.logger; exports.scanDir = _chunkR34R7QPDcjs.scanDir; exports.setDbClient = _chunkFQFKHPLRcjs.setDbClient; exports.transaction = _chunkFQFKHPLRcjs.transaction; exports.workerCount = workerCount;
1141
1143
  //# sourceMappingURL=index.cjs.map