express-file-cluster 0.9.1 → 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 (61) 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 +12 -1
  4. package/dist/auth/index.d.ts +12 -1
  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/cli/index.cjs +17 -65
  11. package/dist/cli/index.cjs.map +1 -1
  12. package/dist/cli/index.js +4 -52
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/docs/api-reference/auth.md +35 -0
  15. package/dist/docs/cli/add.md +2 -2
  16. package/dist/docs/guides/authentication.md +30 -4
  17. package/dist/docs/index.md +1 -1
  18. package/dist/docs/skills/SKILL.md +2 -2
  19. package/dist/docs/skills/api-surface.md +8 -0
  20. package/dist/index.cjs +8 -8
  21. package/dist/index.js +1 -1
  22. package/dist/registry/index.json +1 -1
  23. package/dist/registry/js-mongo/admin-users.json +1 -1
  24. package/dist/registry/js-mongo/auth.json +1 -1
  25. package/dist/registry/js-mongo/auth@apple.json +1 -1
  26. package/dist/registry/js-mongo/auth@google.json +1 -1
  27. package/dist/registry/js-mongo/email-client.json +1 -1
  28. package/dist/registry/js-mongo/forgot-password.json +1 -1
  29. package/dist/registry/js-pg-model/admin-users.json +1 -1
  30. package/dist/registry/js-pg-model/auth.json +1 -1
  31. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  32. package/dist/registry/js-pg-model/auth@google.json +1 -1
  33. package/dist/registry/js-pg-model/email-client.json +1 -1
  34. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  35. package/dist/registry/js-pg-table/admin-users.json +1 -1
  36. package/dist/registry/js-pg-table/auth.json +1 -1
  37. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  38. package/dist/registry/js-pg-table/auth@google.json +1 -1
  39. package/dist/registry/js-pg-table/email-client.json +1 -1
  40. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  41. package/dist/registry/ts-mongo/admin-users.json +1 -1
  42. package/dist/registry/ts-mongo/auth.json +1 -1
  43. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  44. package/dist/registry/ts-mongo/auth@google.json +1 -1
  45. package/dist/registry/ts-mongo/email-client.json +1 -1
  46. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  47. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  48. package/dist/registry/ts-pg-model/auth.json +1 -1
  49. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  50. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  51. package/dist/registry/ts-pg-model/email-client.json +1 -1
  52. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  53. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  54. package/dist/registry/ts-pg-table/auth.json +1 -1
  55. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  56. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  57. package/dist/registry/ts-pg-table/email-client.json +1 -1
  58. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  59. package/package.json +3 -3
  60. package/dist/chunk-2J3HHQKP.cjs.map +0 -1
  61. 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`.
@@ -99,7 +99,7 @@ For `efc add auth:merchant`:
99
99
 
100
100
  - **No existing routes modified:** Existing `/auth/login` and `/auth/register` remain untouched.
101
101
  - **Model registered:** On PostgreSQL with `defineTable`, registers the model in `src/model/index.ts`.
102
- - **Packages ensured:** Adds `bcrypt` (and `@types/bcrypt` in TypeScript) to `package.json` and runs package manager install if missing.
102
+ - **No extra packages:** Passwords are hashed with `hashPassword` / `verifyPassword` from `express-file-cluster/auth` (scrypt, built into Node).
103
103
  - **Tracked in efc.json:** Recorded as `auth:<slug>` in `efc.json`.
104
104
 
105
105
 
@@ -140,7 +140,7 @@ Wrong answers are asked again. A question is only asked for a variable the app d
140
140
 
141
141
  ```json
142
142
  {
143
- "registry": "0.9.0",
143
+ "registry": "0.9.2",
144
144
  "language": "typescript",
145
145
  "database": "postgresql",
146
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
 
@@ -246,3 +250,25 @@ The files belong to you — they're copied into your `src/` just like `efc add a
246
250
 
247
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.
248
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).
@@ -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,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), 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.
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
44
  **Not yet implemented (Phase 3+):** WebSockets, plugins, OpenAPI generation, OpenTelemetry, `efc lint`, `efc deploy`.
@@ -263,6 +263,14 @@ function configureAuth(config: { secret: string; strategy: AuthStrategy; expires
263
263
  // Returns undefined outside a request, or on a route that never ran requireAuth.
264
264
  // Also what powers the '$currentUser'/'$currentUser.<key>' defineModel default codes.
265
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
266
274
  ```
267
275
 
268
276
  Cookie name: `efc_token`. Algorithm: HS256. Library: `jose`.
package/dist/index.cjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
 
6
6
 
7
- var _chunk2J3HHQKPcjs = require('./chunk-2J3HHQKP.cjs');
7
+ var _chunkANUSWEAPcjs = require('./chunk-ANUSWEAP.cjs');
8
8
 
9
9
 
10
10
  var _chunkR34R7QPDcjs = require('./chunk-R34R7QPD.cjs');
@@ -869,7 +869,7 @@ function cacheResponse(options) {
869
869
  }
870
870
  const key = RESPONSE_PREFIX + scope + (opts.key ? opts.key(req) : req.originalUrl);
871
871
  void (async () => {
872
- const hit = await _chunk2J3HHQKPcjs.cache.get(key);
872
+ const hit = await _chunkANUSWEAPcjs.cache.get(key);
873
873
  if (hit) {
874
874
  res.setHeader("X-Cache", "HIT");
875
875
  res.status(hit.status).json(hit.body);
@@ -878,7 +878,7 @@ function cacheResponse(options) {
878
878
  res.setHeader("X-Cache", "MISS");
879
879
  const json = res.json.bind(res);
880
880
  res.json = (body) => {
881
- if (res.statusCode === 200) void _chunk2J3HHQKPcjs.cache.set(key, { status: 200, body }, { ttl: opts.ttl });
881
+ if (res.statusCode === 200) void _chunkANUSWEAPcjs.cache.set(key, { status: 200, body }, { ttl: opts.ttl });
882
882
  return json(body);
883
883
  };
884
884
  next();
@@ -956,7 +956,7 @@ async function ignite(config) {
956
956
  _chunkVQSWSYK6cjs.configureQueryLog.call(void 0, config.logging);
957
957
  if (clusterEnabled && _cluster2.default.isPrimary) {
958
958
  if (config.cache && config.cache.backend === "memory") {
959
- _chunk2J3HHQKPcjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
959
+ _chunkANUSWEAPcjs.servePrimaryCache.call(void 0, _nullishCoalesce(config.cache.maxEntries, () => ( 1e4)));
960
960
  }
961
961
  runMaster({
962
962
  workers: _nullishCoalesce(workers, () => ( _os2.default.cpus().length)),
@@ -1008,10 +1008,10 @@ async function ignite(config) {
1008
1008
  _chunkRTF7PHS2cjs.setDbClient.call(void 0, pool);
1009
1009
  }
1010
1010
  if (config.cache) {
1011
- await _chunk2J3HHQKPcjs.configureCache.call(void 0, config.cache);
1011
+ await _chunkANUSWEAPcjs.configureCache.call(void 0, config.cache);
1012
1012
  }
1013
1013
  if (jwtSecret) {
1014
- _chunk2J3HHQKPcjs.configureAuth.call(void 0, {
1014
+ _chunkANUSWEAPcjs.configureAuth.call(void 0, {
1015
1015
  secret: jwtSecret,
1016
1016
  strategy: authStrategy,
1017
1017
  expiresIn: _nullishCoalesce(config.jwtExpiresIn, () => ( "7d")),
@@ -1103,7 +1103,7 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1103
1103
  server.closeIdleConnections();
1104
1104
  server.close(() => {
1105
1105
  _chunkYL37D6KMcjs.getLogger.call(void 0, ).info("Server closed");
1106
- Promise.all([_chunkT4OHFU5Tcjs.closeBullMQ.call(void 0, ), _chunkTYR2GZZEcjs.closePgBoss.call(void 0, ), _chunk2J3HHQKPcjs.closeCache.call(void 0, )]).catch((err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
1106
+ Promise.all([_chunkT4OHFU5Tcjs.closeBullMQ.call(void 0, ), _chunkTYR2GZZEcjs.closePgBoss.call(void 0, ), _chunkANUSWEAPcjs.closeCache.call(void 0, )]).catch((err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, "Task backend close failed")).finally(() => process.exit(0));
1107
1107
  });
1108
1108
  setTimeout(() => {
1109
1109
  _chunkYL37D6KMcjs.getLogger.call(void 0, ).error("Forced exit after timeout");
@@ -1141,5 +1141,5 @@ function gracefulShutdown(server, timeoutMs = 1e4) {
1141
1141
 
1142
1142
 
1143
1143
 
1144
- exports.HttpError = _chunkX2US4RAMcjs.HttpError; exports.ModelValidationError = _chunkX2US4RAMcjs.ModelValidationError; exports.cache = _chunk2J3HHQKPcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkRTF7PHS2cjs.db; exports.defineCollection = _chunkRTF7PHS2cjs.defineCollection; exports.defineModel = _chunkRTF7PHS2cjs.defineModel; exports.defineTable = _chunkRTF7PHS2cjs.defineTable; exports.getDbClient = _chunkRTF7PHS2cjs.getDbClient; exports.getLogger = _chunkYL37D6KMcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkX2US4RAMcjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkYL37D6KMcjs.logger; exports.scanDir = _chunkR34R7QPDcjs.scanDir; exports.setDbClient = _chunkRTF7PHS2cjs.setDbClient; exports.transaction = _chunkRTF7PHS2cjs.transaction; exports.workerCount = workerCount;
1144
+ exports.HttpError = _chunkX2US4RAMcjs.HttpError; exports.ModelValidationError = _chunkX2US4RAMcjs.ModelValidationError; exports.cache = _chunkANUSWEAPcjs.cache; exports.cacheResponse = cacheResponse; exports.compose = compose; exports.db = _chunkRTF7PHS2cjs.db; exports.defineCollection = _chunkRTF7PHS2cjs.defineCollection; exports.defineModel = _chunkRTF7PHS2cjs.defineModel; exports.defineTable = _chunkRTF7PHS2cjs.defineTable; exports.getDbClient = _chunkRTF7PHS2cjs.getDbClient; exports.getLogger = _chunkYL37D6KMcjs.getLogger; exports.gracefulShutdown = gracefulShutdown; exports.ignite = ignite; exports.isHttpError = _chunkX2US4RAMcjs.isHttpError; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.logger = _chunkYL37D6KMcjs.logger; exports.scanDir = _chunkR34R7QPDcjs.scanDir; exports.setDbClient = _chunkRTF7PHS2cjs.setDbClient; exports.transaction = _chunkRTF7PHS2cjs.transaction; exports.workerCount = workerCount;
1145
1145
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  configureAuth,
5
5
  configureCache,
6
6
  servePrimaryCache
7
- } from "./chunk-RSZB7VAO.js";
7
+ } from "./chunk-ATL4GYFU.js";
8
8
  import {
9
9
  scanDir
10
10
  } from "./chunk-RS4MXCPW.js";
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.9.1",
2
+ "version": "0.9.2",
3
3
  "variants": [
4
4
  {
5
5
  "key": "ts-mongo",
@@ -1 +1 @@
1
- {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false, log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport bcrypt from 'bcrypt';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n if (!name || !email || !password) return res.status(400).json({ error: 'name, email and password are required' });\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await bcrypt.hash(password, 10);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false, log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n if (!name || !email || !password) return res.status(400).json({ error: 'name, email and password are required' });\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport bcrypt from 'bcrypt';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await bcrypt.compare(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await bcrypt.compare(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import bcrypt from 'bcrypt';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await bcrypt.hash(password, 10);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{"bcrypt":"^5.1.0"},"devDependencies":{},"env":[]}
1
+ {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport bcrypt from 'bcrypt';\nimport { HttpError } from 'express-file-cluster';\nimport { issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await bcrypt.hash(randomToken(), 10),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
1
+ {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
@@ -1 +1 @@
1
- {"name":"auth@google","files":[{"path":"src/api/auth/google/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req, res) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true,\n name: payload.name,\n });\n res.redirect(successRedirect());\n};\n"},{"path":"src/api/auth/google/index.js","content":"import { pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport bcrypt from 'bcrypt';\nimport { HttpError } from 'express-file-cluster';\nimport { issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await bcrypt.hash(randomToken(), 10),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
1
+ {"name":"auth@google","files":[{"path":"src/api/auth/google/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req, res) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true,\n name: payload.name,\n });\n res.redirect(successRedirect());\n};\n"},{"path":"src/api/auth/google/index.js","content":"import { pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
@@ -1 +1 @@
1
- {"name":"email-client","files":[{"path":"src/tasks/SendEmail.js","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^6.9.0"},"devDependencies":{},"env":[{"key":"APP_URL","value":"http://localhost:3000","example":"http://localhost:3000"},{"key":"SMTP_HOST","value":"smtp.gmail.com","example":"smtp.gmail.com"},{"key":"SMTP_PORT","value":"465","example":"465"},{"key":"SMTP_USER","value":"","example":"your@email.com"},{"key":"SMTP_PASS","value":" # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords","example":"your_16_char_app_password # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords"},{"key":"SMTP_FROM","value":"noreply@example.com","example":"noreply@yourapp.com"}]}
1
+ {"name":"email-client","files":[{"path":"src/tasks/SendEmail.js","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^10.2.1"},"devDependencies":{},"env":[{"key":"APP_URL","value":"http://localhost:3000","example":"http://localhost:3000"},{"key":"SMTP_HOST","value":"smtp.gmail.com","example":"smtp.gmail.com"},{"key":"SMTP_PORT","value":"465","example":"465"},{"key":"SMTP_USER","value":"","example":"your@email.com"},{"key":"SMTP_PASS","value":" # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords","example":"your_16_char_app_password # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords"},{"key":"SMTP_FROM","value":"noreply@example.com","example":"noreply@yourapp.com"}]}
@@ -1 +1 @@
1
- {"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req, res) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import bcrypt from 'bcrypt';\nimport { revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body;\n if (!token || !password) return res.status(400).json({ error: 'token and password are required' });\n\n const user = await User.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await bcrypt.hash(password, 10);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req, res) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body;\n if (!token || !password) return res.status(400).json({ error: 'token and password are required' });\n\n const user = await User.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false, log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport bcrypt from 'bcrypt';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n if (!name || !email || !password) return res.status(400).json({ error: 'name, email and password are required' });\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await bcrypt.hash(password, 10);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false, log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n if (!name || !email || !password) return res.status(400).json({ error: 'name, email and password are required' });\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport bcrypt from 'bcrypt';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await bcrypt.compare(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await bcrypt.compare(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import bcrypt from 'bcrypt';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await bcrypt.hash(password, 10);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{"bcrypt":"^5.1.0"},"devDependencies":{},"env":[]}
1
+ {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req, res) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport bcrypt from 'bcrypt';\nimport { HttpError } from 'express-file-cluster';\nimport { issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await bcrypt.hash(randomToken(), 10),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
1
+ {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req, res) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect() {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}