express-file-cluster 0.9.3 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/dist/auth/index.cjs +6 -7
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +7 -2
  4. package/dist/auth/index.d.ts +7 -2
  5. package/dist/auth/index.js +5 -6
  6. package/dist/{chunk-QL6EWT4B.cjs → chunk-4DOHQU6I.cjs} +9 -7
  7. package/dist/chunk-4DOHQU6I.cjs.map +1 -0
  8. package/dist/chunk-73XJUT2S.js +366 -0
  9. package/dist/chunk-73XJUT2S.js.map +1 -0
  10. package/dist/{chunk-ATL4GYFU.js → chunk-7KC2H76D.js} +50 -8
  11. package/dist/chunk-7KC2H76D.js.map +1 -0
  12. package/dist/{chunk-TYR2GZZE.cjs → chunk-7KO4DJRJ.cjs} +19 -14
  13. package/dist/chunk-7KO4DJRJ.cjs.map +1 -0
  14. package/dist/{chunk-UBQYQPBU.js → chunk-ATVD2HGC.js} +4 -4
  15. package/dist/{chunk-R34R7QPD.cjs → chunk-DCJOWFVD.cjs} +3 -3
  16. package/dist/{chunk-R34R7QPD.cjs.map → chunk-DCJOWFVD.cjs.map} +1 -1
  17. package/dist/chunk-DUADUR6R.cjs +366 -0
  18. package/dist/chunk-DUADUR6R.cjs.map +1 -0
  19. package/dist/{chunk-BBSZLGZW.js → chunk-EGSSZUVO.js} +8 -6
  20. package/dist/chunk-EGSSZUVO.js.map +1 -0
  21. package/dist/{chunk-TI24L4XE.cjs → chunk-GBI77W5T.cjs} +6 -2
  22. package/dist/chunk-GBI77W5T.cjs.map +1 -0
  23. package/dist/{chunk-RTF7PHS2.cjs → chunk-HBCY7ILD.cjs} +306 -119
  24. package/dist/chunk-HBCY7ILD.cjs.map +1 -0
  25. package/dist/{chunk-ANUSWEAP.cjs → chunk-KFVFP2Q7.cjs} +59 -17
  26. package/dist/chunk-KFVFP2Q7.cjs.map +1 -0
  27. package/dist/{chunk-RS4MXCPW.js → chunk-NI2BNGGV.js} +2 -2
  28. package/dist/{chunk-X2US4RAM.cjs → chunk-NKLOE4AK.cjs} +11 -13
  29. package/dist/chunk-NKLOE4AK.cjs.map +1 -0
  30. package/dist/{chunk-RRQ2RK5M.js → chunk-PGJQK36V.js} +195 -8
  31. package/dist/chunk-PGJQK36V.js.map +1 -0
  32. package/dist/{chunk-QKQZF573.js → chunk-QDEDOHP7.js} +4 -6
  33. package/dist/chunk-QDEDOHP7.js.map +1 -0
  34. package/dist/{chunk-UTM4PEVG.js → chunk-R4XO4SVM.js} +10 -5
  35. package/dist/chunk-R4XO4SVM.js.map +1 -0
  36. package/dist/chunk-R52CUEGT.js +74 -0
  37. package/dist/chunk-R52CUEGT.js.map +1 -0
  38. package/dist/{chunk-HBYSKULC.js → chunk-RAB44UGX.js} +5 -1
  39. package/dist/chunk-RAB44UGX.js.map +1 -0
  40. package/dist/{chunk-7YEX4MQV.cjs → chunk-WBLUGOAG.cjs} +42 -6
  41. package/dist/chunk-WBLUGOAG.cjs.map +1 -0
  42. package/dist/{chunk-T4OHFU5T.cjs → chunk-YK4ZM3CA.cjs} +15 -15
  43. package/dist/{chunk-T4OHFU5T.cjs.map → chunk-YK4ZM3CA.cjs.map} +1 -1
  44. package/dist/cli/db-runner.cjs +2012 -120
  45. package/dist/cli/db-runner.cjs.map +1 -1
  46. package/dist/cli/db-runner.js +1989 -97
  47. package/dist/cli/db-runner.js.map +1 -1
  48. package/dist/cli/index.cjs +101 -43
  49. package/dist/cli/index.cjs.map +1 -1
  50. package/dist/cli/index.js +80 -22
  51. package/dist/cli/index.js.map +1 -1
  52. package/dist/docs/api-reference/auth.md +10 -8
  53. package/dist/docs/api-reference/collection.md +44 -1
  54. package/dist/docs/api-reference/ignite.md +22 -3
  55. package/dist/docs/api-reference/types.md +99 -0
  56. package/dist/docs/cli/add.md +1 -1
  57. package/dist/docs/cli/db.md +2 -2
  58. package/dist/docs/contributing/index.md +1 -1
  59. package/dist/docs/core-concepts/background-tasks.md +6 -3
  60. package/dist/docs/getting-started/index.md +3 -2
  61. package/dist/docs/guides/authentication.md +34 -24
  62. package/dist/docs/guides/caching.md +32 -1
  63. package/dist/docs/guides/database.md +14 -0
  64. package/dist/docs/guides/feature-matrix.md +58 -0
  65. package/dist/docs/guides/migrations.md +23 -2
  66. package/dist/docs/guides/oauth.md +15 -1
  67. package/dist/docs/guides/which-api.md +2 -2
  68. package/dist/docs/index.md +4 -1
  69. package/dist/docs/skills/SKILL.md +2 -2
  70. package/dist/docs/skills/api-surface.md +10 -4
  71. package/dist/docs/skills/auth-internals.md +3 -3
  72. package/dist/docs/skills/tasks-internals.md +4 -3
  73. package/dist/docs/skills/what-not-to-invent.md +4 -3
  74. package/dist/docs/versioning.md +42 -0
  75. package/dist/index.cjs +144 -51
  76. package/dist/index.cjs.map +1 -1
  77. package/dist/index.d.cts +204 -3
  78. package/dist/index.d.ts +204 -3
  79. package/dist/index.js +107 -14
  80. package/dist/index.js.map +1 -1
  81. package/dist/pgboss-backend-FW42SBSM.js +14 -0
  82. package/dist/pgboss-backend-RVHUBJTU.cjs +14 -0
  83. package/dist/{pgboss-backend-TCHI7CHM.cjs.map → pgboss-backend-RVHUBJTU.cjs.map} +1 -1
  84. package/dist/registry/index.json +34 -3
  85. package/dist/registry/js-mongo/account-security.json +1 -1
  86. package/dist/registry/js-mongo/admin-users.json +1 -1
  87. package/dist/registry/js-mongo/auth.json +1 -1
  88. package/dist/registry/js-mongo/auth@apple.json +1 -1
  89. package/dist/registry/js-mongo/auth@google.json +1 -1
  90. package/dist/registry/js-mongo/email-verification.json +1 -1
  91. package/dist/registry/js-mongo/forgot-password.json +1 -1
  92. package/dist/registry/js-mongo/user-profile.json +1 -1
  93. package/dist/registry/js-mongo-collection/_base.json +1 -0
  94. package/dist/registry/js-mongo-collection/account-security.json +1 -0
  95. package/dist/registry/js-mongo-collection/account-settings.json +1 -0
  96. package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
  97. package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
  98. package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
  99. package/dist/registry/js-mongo-collection/admin-content.json +1 -0
  100. package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
  101. package/dist/registry/js-mongo-collection/admin-support.json +1 -0
  102. package/dist/registry/js-mongo-collection/admin-system.json +1 -0
  103. package/dist/registry/js-mongo-collection/admin-users.json +1 -0
  104. package/dist/registry/js-mongo-collection/admin.json +1 -0
  105. package/dist/registry/js-mongo-collection/auth.json +1 -0
  106. package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
  107. package/dist/registry/js-mongo-collection/auth@google.json +1 -0
  108. package/dist/registry/js-mongo-collection/billing.json +1 -0
  109. package/dist/registry/js-mongo-collection/email-client.json +1 -0
  110. package/dist/registry/js-mongo-collection/email-verification.json +1 -0
  111. package/dist/registry/js-mongo-collection/files.json +1 -0
  112. package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
  113. package/dist/registry/js-mongo-collection/notifications.json +1 -0
  114. package/dist/registry/js-mongo-collection/support.json +1 -0
  115. package/dist/registry/js-mongo-collection/user-profile.json +1 -0
  116. package/dist/registry/js-pg-model/account-security.json +1 -1
  117. package/dist/registry/js-pg-model/admin-users.json +1 -1
  118. package/dist/registry/js-pg-model/auth.json +1 -1
  119. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  120. package/dist/registry/js-pg-model/auth@google.json +1 -1
  121. package/dist/registry/js-pg-model/email-verification.json +1 -1
  122. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  123. package/dist/registry/js-pg-model/user-profile.json +1 -1
  124. package/dist/registry/js-pg-table/account-security.json +1 -1
  125. package/dist/registry/js-pg-table/admin-users.json +1 -1
  126. package/dist/registry/js-pg-table/auth.json +1 -1
  127. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  128. package/dist/registry/js-pg-table/auth@google.json +1 -1
  129. package/dist/registry/js-pg-table/email-verification.json +1 -1
  130. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  131. package/dist/registry/js-pg-table/user-profile.json +1 -1
  132. package/dist/registry/ts-mongo/account-security.json +1 -1
  133. package/dist/registry/ts-mongo/admin-users.json +1 -1
  134. package/dist/registry/ts-mongo/auth.json +1 -1
  135. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  136. package/dist/registry/ts-mongo/auth@google.json +1 -1
  137. package/dist/registry/ts-mongo/email-verification.json +1 -1
  138. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  139. package/dist/registry/ts-mongo/user-profile.json +1 -1
  140. package/dist/registry/ts-mongo-collection/_base.json +1 -0
  141. package/dist/registry/ts-mongo-collection/account-security.json +1 -0
  142. package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
  143. package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
  144. package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
  145. package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
  146. package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
  147. package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
  148. package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
  149. package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
  150. package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
  151. package/dist/registry/ts-mongo-collection/admin.json +1 -0
  152. package/dist/registry/ts-mongo-collection/auth.json +1 -0
  153. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
  154. package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
  155. package/dist/registry/ts-mongo-collection/billing.json +1 -0
  156. package/dist/registry/ts-mongo-collection/email-client.json +1 -0
  157. package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
  158. package/dist/registry/ts-mongo-collection/files.json +1 -0
  159. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
  160. package/dist/registry/ts-mongo-collection/notifications.json +1 -0
  161. package/dist/registry/ts-mongo-collection/support.json +1 -0
  162. package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
  163. package/dist/registry/ts-pg-model/account-security.json +1 -1
  164. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  165. package/dist/registry/ts-pg-model/auth.json +1 -1
  166. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  167. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  168. package/dist/registry/ts-pg-model/email-verification.json +1 -1
  169. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  170. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  171. package/dist/registry/ts-pg-table/account-security.json +1 -1
  172. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  173. package/dist/registry/ts-pg-table/auth.json +1 -1
  174. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  175. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  176. package/dist/registry/ts-pg-table/email-verification.json +1 -1
  177. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  178. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  179. package/dist/tasks/index.cjs +4 -2
  180. package/dist/tasks/index.cjs.map +1 -1
  181. package/dist/tasks/index.d.cts +4 -2
  182. package/dist/tasks/index.d.ts +4 -2
  183. package/dist/tasks/index.js +3 -1
  184. package/dist/thread-runner.cjs +8 -0
  185. package/dist/thread-runner.cjs.map +1 -0
  186. package/dist/thread-runner.d.cts +3 -0
  187. package/dist/thread-runner.d.ts +3 -0
  188. package/dist/thread-runner.js +8 -0
  189. package/dist/thread-runner.js.map +1 -0
  190. package/dist/{types-BY-ObnZH.d.ts → types-Bnxvj3l0.d.cts} +14 -2
  191. package/dist/{types-BY-ObnZH.d.cts → types-Bnxvj3l0.d.ts} +14 -2
  192. package/package.json +1 -1
  193. package/dist/chunk-277BSYVH.js +0 -127
  194. package/dist/chunk-277BSYVH.js.map +0 -1
  195. package/dist/chunk-7YEX4MQV.cjs.map +0 -1
  196. package/dist/chunk-ANUSWEAP.cjs.map +0 -1
  197. package/dist/chunk-ATL4GYFU.js.map +0 -1
  198. package/dist/chunk-BBSZLGZW.js.map +0 -1
  199. package/dist/chunk-HBYSKULC.js.map +0 -1
  200. package/dist/chunk-HXV543HZ.js +0 -177
  201. package/dist/chunk-HXV543HZ.js.map +0 -1
  202. package/dist/chunk-LJNSJFOL.js +0 -38
  203. package/dist/chunk-LJNSJFOL.js.map +0 -1
  204. package/dist/chunk-QKQZF573.js.map +0 -1
  205. package/dist/chunk-QL6EWT4B.cjs.map +0 -1
  206. package/dist/chunk-RRQ2RK5M.js.map +0 -1
  207. package/dist/chunk-RTF7PHS2.cjs.map +0 -1
  208. package/dist/chunk-TI24L4XE.cjs.map +0 -1
  209. package/dist/chunk-TYR2GZZE.cjs.map +0 -1
  210. package/dist/chunk-UTM4PEVG.js.map +0 -1
  211. package/dist/chunk-VQSWSYK6.cjs +0 -177
  212. package/dist/chunk-VQSWSYK6.cjs.map +0 -1
  213. package/dist/chunk-X2US4RAM.cjs.map +0 -1
  214. package/dist/chunk-YL37D6KM.cjs +0 -127
  215. package/dist/chunk-YL37D6KM.cjs.map +0 -1
  216. package/dist/pgboss-backend-QKBXVJ6B.js +0 -14
  217. package/dist/pgboss-backend-TCHI7CHM.cjs +0 -14
  218. /package/dist/{chunk-UBQYQPBU.js.map → chunk-ATVD2HGC.js.map} +0 -0
  219. /package/dist/{chunk-RS4MXCPW.js.map → chunk-NI2BNGGV.js.map} +0 -0
  220. /package/dist/{pgboss-backend-QKBXVJ6B.js.map → pgboss-backend-FW42SBSM.js.map} +0 -0
@@ -1 +1 @@
1
- {"name":"auth","files":[{"path":"src/api/auth/login.ts","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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(\n res: Response,\n model: { update: (args: { where: { id: string }; data: Record<string, unknown> }) => Promise<unknown> },\n id: string,\n): Promise<void> {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update({ where: { id }, data: { 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: Request, res: Response) => {\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.findFirst({ where: { 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.findFirst({ where: { 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.ts","content":"import { revokeSession } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\n res.json({ user: (req as any).user });\n};\n"},{"path":"src/api/auth/register.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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.findFirst({ where: { 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({ data: { 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.ts","content":"import { defineTable } from 'express-file-cluster';\n\nexport const Admin = defineTable('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.ts","content":"import { defineTable } from 'express-file-cluster';\n\nexport const User = defineTable('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
+ {"name":"auth","files":[{"path":"src/api/auth/login.ts","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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\n// 10 attempts per 15 minutes per address and account. Keyed on the email too, so behind a\n// proxy without TRUST_PROXY (every client then has the proxy's IP) it still limits one\n// account at a time, never everyone.\nexport const middlewares = [\n rateLimit({\n window: '15m',\n max: 10,\n key: (req) => `${req.ip}:${String(req.body?.email ?? '').toLowerCase()}`,\n }),\n];\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(\n res: Response,\n model: { update: (args: { where: { id: string }; data: Record<string, unknown> }) => Promise<unknown> },\n id: string,\n): Promise<string> {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update({ where: { id }, data: { 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 return refreshToken;\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {\n return res.status(400).json({ error: 'email and password are required' });\n }\n\n const admin = await Admin.findFirst({ where: { 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 const token = await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n const refreshToken = await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin', ...(token ? { token, refreshToken } : {}) });\n }\n\n const user = await User.findFirst({ where: { 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 const token = await issueToken(res, { id: user.id, role: user.role, email: user.email });\n const refreshToken = await issueRefreshToken(res, User, user.id);\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({ message: 'Logged in', ...(token ? { token, refreshToken } : {}) });\n};\n"},{"path":"src/api/auth/logout.ts","content":"import { revokeSession } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\n res.json({ user: (req as any).user });\n};\n"},{"path":"src/api/auth/register.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\n const { name, email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof name !== 'string' || typeof email !== 'string' || typeof password !== 'string' || !name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findFirst({ where: { 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({ data: { 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: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.ts","content":"import { defineTable } from 'express-file-cluster';\n\nexport const Admin = defineTable('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.ts","content":"import { defineTable } from 'express-file-cluster';\n\nexport const User = defineTable('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.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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(): Promise<string> {\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: Request, res: Response) => {\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()) as { id_token: string };\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: string | undefined;\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 as string | undefined,\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.ts","content":"import type { Request, Response } from 'express';\nimport { randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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.ts","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\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\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\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: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\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: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\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: Response, profile: OAuthProfile): Promise<void> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : 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.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: 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(): string {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('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 user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\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.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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(): Promise<string> {\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: Request, res: Response) => {\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()) as { id_token: string };\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: string | undefined;\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 const token = await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/apple/index.ts","content":"import type { Request, Response } from 'express';\nimport { appChallengeFrom, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req: Request, res: Response) => {\n const appChallenge = appChallengeFrom(req.query);\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce, ...(appChallenge ? { appChallenge } : {}) }, 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/api/auth/oauth/exchange.ts","content":"import type { Request, Response } from 'express';\nimport { exchangeCode } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Bearer apps: trade the one-time code from the sign-in redirect (plus the PKCE code_verifier) for a token.' },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\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\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n /** Bearer apps: the S256 challenge of a verifier only the app knows (app ↔ this server). */\n appChallenge?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\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: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\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: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\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: Response, profile: OAuthProfile): Promise<string | undefined> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : 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.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: user.id,\n } });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n // http-only: sets the cookie, returns undefined. bearer: returns the token.\n return issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/**\n * Bearer apps start sign-in with `?code_challenge=<base64url SHA-256 of a random verifier>`\n * (PKCE, RFC 7636, between the app and this server). Only the app holding the verifier can\n * redeem the sign-in code — another app catching the myapp:// redirect can't.\n */\nexport function appChallengeFrom(query: Request['query']): string | undefined {\n const challenge = query.code_challenge;\n if (challenge === undefined) return undefined;\n if (typeof challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n throw new HttpError(400, 'code_challenge must be the base64url SHA-256 of your code_verifier');\n }\n return challenge;\n}\n\n/**\n * Where the browser goes once signed in. With authStrategy 'bearer' the JWT never goes in the\n * URL (history, screenshots, logs): it gets a one-time code, valid for a minute, which the app\n * that started the sign-in trades for the token at POST /auth/oauth/exchange.\n */\nexport async function successRedirect(\n token?: string,\n appChallenge?: string,\n): Promise<string> {\n const to = process.env.OAUTH_SUCCESS_REDIRECT || '/';\n if (!token) return to;\n if (!appChallenge) {\n throw new HttpError(\n 400,\n 'Bearer sign-in needs a code_challenge — start at /auth/<provider>?code_challenge=…',\n );\n }\n const code = randomToken();\n await cache.set(`oauth:code:${code}`, { token, appChallenge }, { ttl: CODE_TTL_S });\n return `${to}#code=${code}`;\n}\n\n/**\n * The token for a one-time sign-in code, given the verifier behind the challenge the sign-in\n * started with. Once: a second use (or after a minute) gets 400.\n */\nexport async function exchangeCode(code: unknown, verifier: unknown): Promise<string> {\n if (typeof code !== 'string' || !code) throw new HttpError(400, 'code is required');\n if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {\n throw new HttpError(400, 'code_verifier is required (43-128 characters)');\n }\n const key = `oauth:code:${code}`;\n const saved = await cache.get<{ token: string; appChallenge: string }>(key);\n const expected = Buffer.from(saved?.appChallenge ?? '');\n const actual = Buffer.from(pkceChallenge(verifier));\n // A wrong verifier leaves the code alone, so it can't be used to burn someone's sign-in.\n if (!saved || expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {\n throw new HttpError(400, 'Invalid or expired sign-in code');\n }\n // del is atomic: of two requests racing with the same code, only one removes it.\n if ((await cache.del(key)) !== 1) throw new HttpError(400, 'Invalid or expired sign-in code');\n return saved.token;\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('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 user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\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.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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()) as { id_token: string };\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 as string | undefined,\n emailVerified: payload.email_verified === true,\n name: payload.name as string | undefined,\n });\n res.redirect(successRedirect());\n};\n"},{"path":"src/api/auth/google/index.ts","content":"import type { Request, Response } from 'express';\nimport { pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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.ts","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\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\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\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: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\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: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\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: Response, profile: OAuthProfile): Promise<void> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : 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.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: 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(): string {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('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 user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\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.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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()) as { id_token: string };\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 const token = await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true,\n name: payload.name as string | undefined,\n });\n res.redirect(await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/google/index.ts","content":"import type { Request, Response } from 'express';\nimport { appChallengeFrom, pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req: Request, res: Response) => {\n const appChallenge = appChallengeFrom(req.query);\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier, ...(appChallenge ? { appChallenge } : {}) });\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/api/auth/oauth/exchange.ts","content":"import type { Request, Response } from 'express';\nimport { exchangeCode } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Bearer apps: trade the one-time code from the sign-in redirect (plus the PKCE code_verifier) for a token.' },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\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\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n /** Bearer apps: the S256 challenge of a verifier only the app knows (app ↔ this server). */\n appChallenge?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\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: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\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: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\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: Response, profile: OAuthProfile): Promise<string | undefined> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : 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.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: user.id,\n } });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n // http-only: sets the cookie, returns undefined. bearer: returns the token.\n return issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/**\n * Bearer apps start sign-in with `?code_challenge=<base64url SHA-256 of a random verifier>`\n * (PKCE, RFC 7636, between the app and this server). Only the app holding the verifier can\n * redeem the sign-in code — another app catching the myapp:// redirect can't.\n */\nexport function appChallengeFrom(query: Request['query']): string | undefined {\n const challenge = query.code_challenge;\n if (challenge === undefined) return undefined;\n if (typeof challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n throw new HttpError(400, 'code_challenge must be the base64url SHA-256 of your code_verifier');\n }\n return challenge;\n}\n\n/**\n * Where the browser goes once signed in. With authStrategy 'bearer' the JWT never goes in the\n * URL (history, screenshots, logs): it gets a one-time code, valid for a minute, which the app\n * that started the sign-in trades for the token at POST /auth/oauth/exchange.\n */\nexport async function successRedirect(\n token?: string,\n appChallenge?: string,\n): Promise<string> {\n const to = process.env.OAUTH_SUCCESS_REDIRECT || '/';\n if (!token) return to;\n if (!appChallenge) {\n throw new HttpError(\n 400,\n 'Bearer sign-in needs a code_challenge — start at /auth/<provider>?code_challenge=…',\n );\n }\n const code = randomToken();\n await cache.set(`oauth:code:${code}`, { token, appChallenge }, { ttl: CODE_TTL_S });\n return `${to}#code=${code}`;\n}\n\n/**\n * The token for a one-time sign-in code, given the verifier behind the challenge the sign-in\n * started with. Once: a second use (or after a minute) gets 400.\n */\nexport async function exchangeCode(code: unknown, verifier: unknown): Promise<string> {\n if (typeof code !== 'string' || !code) throw new HttpError(400, 'code is required');\n if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {\n throw new HttpError(400, 'code_verifier is required (43-128 characters)');\n }\n const key = `oauth:code:${code}`;\n const saved = await cache.get<{ token: string; appChallenge: string }>(key);\n const expected = Buffer.from(saved?.appChallenge ?? '');\n const actual = Buffer.from(pkceChallenge(verifier));\n // A wrong verifier leaves the code alone, so it can't be used to burn someone's sign-in.\n if (!saved || expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {\n throw new HttpError(400, 'Invalid or expired sign-in code');\n }\n // del is atomic: of two requests racing with the same code, only one removes it.\n if ((await cache.del(key)) !== 1) throw new HttpError(400, 'Invalid or expired sign-in code');\n return saved.token;\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('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 user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\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-verification","files":[{"path":"src/api/auth/verify-email.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Verify an email address using the token from the verification link.',\n request: { query: { token: 'a1b2c3d4' } },\n response: { status: 200, body: { message: 'Email verified' } },\n },\n POST: {\n description: 'Resend the verification email to a given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Verification email sent' } },\n },\n};\n\nexport const GET = async (req: Request, res: Response) => {\n const { token } = req.query;\n if (!token || typeof token !== 'string') return res.status(400).json({ error: 'token is required' });\n\n const user = await User.findFirst({ where: { verifyToken: token } });\n if (!user) return res.status(400).json({ error: 'Invalid or expired verification token' });\n\n await User.update({ where: { id: user.id }, data: { isVerified: true, verifyToken: '' } });\n res.json({ message: 'Email verified' });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n if (user && !user.isVerified) {\n const verifyToken = crypto.randomBytes(32).toString('hex');\n await User.update({ where: { id: user.id }, data: { verifyToken } });\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: 'Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n }\n\n res.json({ message: 'Verification email sent' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"email-verification","files":[{"path":"src/api/auth/verify-email.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Verify an email address using the token from the verification link.',\n request: { query: { token: 'a1b2c3d4' } },\n response: { status: 200, body: { message: 'Email verified' } },\n },\n POST: {\n description: 'Resend the verification email to a given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Verification email sent' } },\n },\n};\n\nexport const GET = async (req: Request, res: Response) => {\n const { token } = req.query;\n if (!token || typeof token !== 'string') return res.status(400).json({ error: 'token is required' });\n\n const user = await User.findFirst({ where: { verifyToken: token } });\n if (!user) return res.status(400).json({ error: 'Invalid or expired verification token' });\n\n await User.update({ where: { id: user.id }, data: { isVerified: true, verifyToken: '' } });\n res.json({ message: 'Email verified' });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n if (user && !user.isVerified) {\n const verifyToken = crypto.randomBytes(32).toString('hex');\n await User.update({ where: { id: user.id }, data: { verifyToken } });\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: 'Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n }\n\n res.json({ message: 'Verification email sent' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n const admin = user ? null : await Admin.findFirst({ where: { 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({ where: { id: user.id }, data: { resetToken, resetTokenExpiry } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { 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.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\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.findFirst({ where: { resetToken: token } });\n const admin = user ? null : await Admin.findFirst({ where: { 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({ where: { id: user.id }, data: { password: hashed, resetToken: '' } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { 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.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { rateLimit } from 'express-file-cluster';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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\n// 5 reset emails per hour per address — keeps the endpoint from mail-bombing someone.\nexport const middlewares = [\n rateLimit({ window: '1h', max: 5, key: (req) => String(req.body?.email ?? '').toLowerCase() }),\n];\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n const admin = user ? null : await Admin.findFirst({ where: { 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({ where: { id: user.id }, data: { resetToken, resetTokenExpiry } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { 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.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\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: Request, res: Response) => {\n const { token, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof token !== 'string' || typeof password !== 'string' || !token || !password) {\n return res.status(400).json({ error: 'token and password are required' });\n }\n\n const user = await User.findFirst({ where: { resetToken: token } });\n const admin = user ? null : await Admin.findFirst({ where: { 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({ where: { id: user.id }, data: { password: hashed, resetToken: '' } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { 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":"user-profile","files":[{"path":"src/api/user/profile.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: \"Fetch the authenticated user's profile.\",\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n PUT: {\n description: \"Update the authenticated user's profile.\",\n request: { body: { name: 'Jane Doe', email: 'jane@example.com' } },\n response: { status: 200, body: { message: 'Profile updated', user: { id: '1', role: 'user', email: 'jane@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const user = await User.findUnique({ where: { 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: Request, res: Response) => {\n const { id } = (req as any).user;\n const { name, email } = req.body;\n const updated = await User.update({ where: { id }, data: { name, email } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'Profile updated', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"user-profile","files":[{"path":"src/api/user/profile.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: \"Fetch the authenticated user's profile.\",\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n PUT: {\n description: \"Update the authenticated user's profile.\",\n request: { body: { name: 'Jane Doe', email: 'jane@example.com' } },\n response: { status: 200, body: { message: 'Profile updated', user: { id: '1', role: 'user', email: 'jane@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const user = await User.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const { name, email } = req.body;\n const updated = await User.update({ where: { id }, data: { name, email } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = updated;\n res.json({ message: 'Profile updated', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -5,13 +5,15 @@
5
5
 
6
6
 
7
7
 
8
- var _chunkTI24L4XEcjs = require('../chunk-TI24L4XE.cjs');
9
8
 
9
+ var _chunkGBI77W5Tcjs = require('../chunk-GBI77W5T.cjs');
10
10
 
11
11
 
12
12
 
13
13
 
14
14
 
15
15
 
16
- exports.defineTask = _chunkTI24L4XEcjs.defineTask; exports.enqueue = _chunkTI24L4XEcjs.enqueue; exports.listTasks = _chunkTI24L4XEcjs.listTasks; exports.registerTask = _chunkTI24L4XEcjs.registerTask; exports.setEnqueueImpl = _chunkTI24L4XEcjs.setEnqueueImpl; exports.taskRegistry = _chunkTI24L4XEcjs.taskRegistry;
16
+
17
+
18
+ exports.ENQUEUE_BRIDGE = _chunkGBI77W5Tcjs.ENQUEUE_BRIDGE; exports.defineTask = _chunkGBI77W5Tcjs.defineTask; exports.enqueue = _chunkGBI77W5Tcjs.enqueue; exports.listTasks = _chunkGBI77W5Tcjs.listTasks; exports.registerTask = _chunkGBI77W5Tcjs.registerTask; exports.setEnqueueImpl = _chunkGBI77W5Tcjs.setEnqueueImpl; exports.taskRegistry = _chunkGBI77W5Tcjs.taskRegistry;
17
19
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/tasks/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACF,yTAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/tasks/index.cjs"}
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/tasks/index.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,oXAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/tasks/index.cjs"}
@@ -1,4 +1,4 @@
1
- import { T as TaskOptions, a as TaskDefinition } from '../types-BY-ObnZH.cjs';
1
+ import { T as TaskOptions, a as TaskDefinition } from '../types-Bnxvj3l0.cjs';
2
2
  import 'express';
3
3
 
4
4
  declare const taskRegistry: Map<string, TaskDefinition<unknown>>;
@@ -10,6 +10,8 @@ type DefineTaskOverload = {
10
10
  declare const defineTask: DefineTaskOverload;
11
11
  type EnqueueImpl = (name: string, payload: unknown) => Promise<void>;
12
12
  declare function setEnqueueImpl(impl: EnqueueImpl): void;
13
+ /** Set inside `{ thread: true }` task threads: forwards enqueue() to the main thread. */
14
+ declare const ENQUEUE_BRIDGE: unique symbol;
13
15
  declare function enqueue<T>(name: string, payload: T): Promise<void>;
14
16
  declare function registerTask(name: string, def: TaskDefinition): void;
15
17
  /**
@@ -25,4 +27,4 @@ declare function listTasks(): ReadonlyArray<{
25
27
  options: TaskOptions;
26
28
  }>;
27
29
 
28
- export { defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
30
+ export { ENQUEUE_BRIDGE, defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
@@ -1,4 +1,4 @@
1
- import { T as TaskOptions, a as TaskDefinition } from '../types-BY-ObnZH.js';
1
+ import { T as TaskOptions, a as TaskDefinition } from '../types-Bnxvj3l0.js';
2
2
  import 'express';
3
3
 
4
4
  declare const taskRegistry: Map<string, TaskDefinition<unknown>>;
@@ -10,6 +10,8 @@ type DefineTaskOverload = {
10
10
  declare const defineTask: DefineTaskOverload;
11
11
  type EnqueueImpl = (name: string, payload: unknown) => Promise<void>;
12
12
  declare function setEnqueueImpl(impl: EnqueueImpl): void;
13
+ /** Set inside `{ thread: true }` task threads: forwards enqueue() to the main thread. */
14
+ declare const ENQUEUE_BRIDGE: unique symbol;
13
15
  declare function enqueue<T>(name: string, payload: T): Promise<void>;
14
16
  declare function registerTask(name: string, def: TaskDefinition): void;
15
17
  /**
@@ -25,4 +27,4 @@ declare function listTasks(): ReadonlyArray<{
25
27
  options: TaskOptions;
26
28
  }>;
27
29
 
28
- export { defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
30
+ export { ENQUEUE_BRIDGE, defineTask, enqueue, listTasks, registerTask, setEnqueueImpl, taskRegistry };
@@ -1,12 +1,14 @@
1
1
  import {
2
+ ENQUEUE_BRIDGE,
2
3
  defineTask,
3
4
  enqueue,
4
5
  listTasks,
5
6
  registerTask,
6
7
  setEnqueueImpl,
7
8
  taskRegistry
8
- } from "../chunk-HBYSKULC.js";
9
+ } from "../chunk-RAB44UGX.js";
9
10
  export {
11
+ ENQUEUE_BRIDGE,
10
12
  defineTask,
11
13
  enqueue,
12
14
  listTasks,
@@ -0,0 +1,8 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkWBLUGOAGcjs = require('./chunk-WBLUGOAG.cjs');
4
+ require('./chunk-GBI77W5T.cjs');
5
+
6
+
7
+ exports.runInThread = _chunkWBLUGOAGcjs.runInThread;
8
+ //# sourceMappingURL=thread-runner.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/thread-runner.cjs"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B,gCAA6B;AAC7B;AACE;AACF,oDAAC","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/thread-runner.cjs"}
@@ -0,0 +1,3 @@
1
+ declare function runInThread(handlerPath: string, payload: unknown): Promise<void>;
2
+
3
+ export { runInThread };
@@ -0,0 +1,3 @@
1
+ declare function runInThread(handlerPath: string, payload: unknown): Promise<void>;
2
+
3
+ export { runInThread };
@@ -0,0 +1,8 @@
1
+ import {
2
+ runInThread
3
+ } from "./chunk-R52CUEGT.js";
4
+ import "./chunk-RAB44UGX.js";
5
+ export {
6
+ runInThread
7
+ };
8
+ //# sourceMappingURL=thread-runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,7 +1,12 @@
1
1
  import { RequestHandler, ErrorRequestHandler } from 'express';
2
2
 
3
3
  type DatabaseEngine = 'mongodb' | 'postgresql';
4
- type AuthStrategy = 'http-only' | 'localStorage';
4
+ /**
5
+ * How clients carry the JWT. `'http-only'`: an http-only cookie (browsers — websites and
6
+ * SPAs). `'bearer'`: an `Authorization: Bearer` header (mobile/desktop apps, API clients).
7
+ * `'localStorage'` is the old name for `'bearer'` and still works.
8
+ */
9
+ type AuthStrategy = 'http-only' | 'bearer' | 'localStorage';
5
10
  type TaskBackend = 'bullmq' | 'pg-boss';
6
11
  interface TaskConfig {
7
12
  backend: TaskBackend;
@@ -90,12 +95,19 @@ interface DatabasePoolConfig {
90
95
  }
91
96
  interface EFCConfig {
92
97
  port?: number;
98
+ /**
99
+ * Express's `trust proxy`: set it when the app runs behind a proxy or load balancer
100
+ * (Render, Fly, Heroku, nginx, a cloud LB) so `req.ip` is the client, not the proxy —
101
+ * `true`, the number of hops, or addresses / subnets. `rateLimit` keys on `req.ip`.
102
+ */
103
+ trustProxy?: boolean | number | string | string[];
93
104
  basePath?: string;
94
105
  dashboard?: boolean;
95
106
  database?: DatabaseEngine;
96
107
  databaseUrl?: string;
97
108
  /** Connection pool settings — per worker, so the total is `max × workers`. */
98
109
  databasePool?: DatabasePoolConfig;
110
+ /** `'http-only'` (cookie, default) or `'bearer'` (Authorization header). */
99
111
  authStrategy?: AuthStrategy;
100
112
  jwtSecret?: string;
101
113
  /** JWT lifetime, e.g. '15m', '1h', '7d'. Default: '7d'. */
@@ -631,4 +643,4 @@ interface MigrationContext {
631
643
  engine: DatabaseEngine;
632
644
  }
633
645
 
634
- export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g, CacheConfig as h, CollectionFieldDefinition as i, CorsConfig as j, DatabasePoolConfig as k, DefaultOperator as l, Filter as m, FilterOperators as n, FindOptions as o, IndexDefinition as p, InferCreate as q, InferRecord as r, MigrationContext as s, ModelCRUD as t, ModelQueryOptions as u, ModelRecord as v, RequestSchema as w, RouteMeta as x, RouteMethodMeta as y, RouteSchema as z };
646
+ export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g, InferRecord as h, CacheConfig as i, CollectionFieldDefinition as j, CorsConfig as k, DatabasePoolConfig as l, DefaultOperator as m, Filter as n, FilterOperators as o, FindOptions as p, IndexDefinition as q, InferCreate as r, MigrationContext as s, ModelCRUD as t, ModelQueryOptions as u, ModelRecord as v, RequestSchema as w, RouteMeta as x, RouteMethodMeta as y, RouteSchema as z };
@@ -1,7 +1,12 @@
1
1
  import { RequestHandler, ErrorRequestHandler } from 'express';
2
2
 
3
3
  type DatabaseEngine = 'mongodb' | 'postgresql';
4
- type AuthStrategy = 'http-only' | 'localStorage';
4
+ /**
5
+ * How clients carry the JWT. `'http-only'`: an http-only cookie (browsers — websites and
6
+ * SPAs). `'bearer'`: an `Authorization: Bearer` header (mobile/desktop apps, API clients).
7
+ * `'localStorage'` is the old name for `'bearer'` and still works.
8
+ */
9
+ type AuthStrategy = 'http-only' | 'bearer' | 'localStorage';
5
10
  type TaskBackend = 'bullmq' | 'pg-boss';
6
11
  interface TaskConfig {
7
12
  backend: TaskBackend;
@@ -90,12 +95,19 @@ interface DatabasePoolConfig {
90
95
  }
91
96
  interface EFCConfig {
92
97
  port?: number;
98
+ /**
99
+ * Express's `trust proxy`: set it when the app runs behind a proxy or load balancer
100
+ * (Render, Fly, Heroku, nginx, a cloud LB) so `req.ip` is the client, not the proxy —
101
+ * `true`, the number of hops, or addresses / subnets. `rateLimit` keys on `req.ip`.
102
+ */
103
+ trustProxy?: boolean | number | string | string[];
93
104
  basePath?: string;
94
105
  dashboard?: boolean;
95
106
  database?: DatabaseEngine;
96
107
  databaseUrl?: string;
97
108
  /** Connection pool settings — per worker, so the total is `max × workers`. */
98
109
  databasePool?: DatabasePoolConfig;
110
+ /** `'http-only'` (cookie, default) or `'bearer'` (Authorization header). */
99
111
  authStrategy?: AuthStrategy;
100
112
  jwtSecret?: string;
101
113
  /** JWT lifetime, e.g. '15m', '1h', '7d'. Default: '7d'. */
@@ -631,4 +643,4 @@ interface MigrationContext {
631
643
  engine: DatabaseEngine;
632
644
  }
633
645
 
634
- export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g, CacheConfig as h, CollectionFieldDefinition as i, CorsConfig as j, DatabasePoolConfig as k, DefaultOperator as l, Filter as m, FilterOperators as n, FindOptions as o, IndexDefinition as p, InferCreate as q, InferRecord as r, MigrationContext as s, ModelCRUD as t, ModelQueryOptions as u, ModelRecord as v, RequestSchema as w, RouteMeta as x, RouteMethodMeta as y, RouteSchema as z };
646
+ export type { AuthStrategy as A, ScalarKeys as B, CollectionSchema as C, DatabaseEngine as D, EFCConfig as E, FieldDefinition as F, GeoPoint as G, SchemaField as H, InferSchema as I, TableFieldDefinition as J, TableRelation as K, LoggingConfig as L, ModelSchema as M, TableSchemaField as N, Validator as O, QueryLogConfig as Q, RouteEntry as R, Simplify as S, TaskOptions as T, Update as U, ValidationIssue as V, TaskDefinition as a, InferCreateInput as b, ModelOptions as c, InferredModel as d, TableSchema as e, TableOptions as f, SortDirection as g, InferRecord as h, CacheConfig as i, CollectionFieldDefinition as j, CorsConfig as k, DatabasePoolConfig as l, DefaultOperator as m, Filter as n, FilterOperators as o, FindOptions as p, IndexDefinition as q, InferCreate as r, MigrationContext as s, ModelCRUD as t, ModelQueryOptions as u, ModelRecord as v, RequestSchema as w, RouteMeta as x, RouteMethodMeta as y, RouteSchema as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-file-cluster",
3
- "version": "0.9.3",
3
+ "version": "0.10.0",
4
4
  "description": "Enterprise-grade, zero-boilerplate backend framework with file-based routing and multi-core clustering",
5
5
  "homepage": "https://efc.prashantadhikari7.com.np/",
6
6
  "repository": {
@@ -1,127 +0,0 @@
1
- // src/context.ts
2
- import { AsyncLocalStorage } from "async_hooks";
3
- var storage = new AsyncLocalStorage();
4
- function runWithContext(ctx, fn) {
5
- return storage.run(ctx, fn);
6
- }
7
- function getRequestContext() {
8
- return storage.getStore();
9
- }
10
- function setCurrentUser(user) {
11
- const store = storage.getStore();
12
- if (store) store.user = user;
13
- }
14
- function getCurrentUser() {
15
- return storage.getStore()?.user;
16
- }
17
-
18
- // src/logger.ts
19
- import cluster from "cluster";
20
- import { randomUUID } from "crypto";
21
- import pc from "picocolors";
22
- import { pino } from "pino";
23
- var LEVEL_LABELS = {
24
- 10: pc.gray("TRACE"),
25
- 20: pc.blue("DEBUG"),
26
- 30: pc.green("INFO "),
27
- 40: pc.yellow("WARN "),
28
- 50: pc.red("ERROR"),
29
- 60: pc.bgRed("FATAL")
30
- };
31
- var OMIT = /* @__PURE__ */ new Set(["level", "time", "msg", "pid", "hostname", "worker", "reqId"]);
32
- function prettyStream(out = process.stdout) {
33
- return {
34
- write(line) {
35
- let rec;
36
- try {
37
- rec = JSON.parse(line);
38
- } catch {
39
- out.write(line);
40
- return;
41
- }
42
- const time = new Date(rec["time"]).toTimeString().slice(0, 8);
43
- const level = LEVEL_LABELS[rec["level"]] ?? String(rec["level"]);
44
- const worker = rec["worker"] !== void 0 ? pc.dim(`[${String(rec["worker"])}] `) : "";
45
- const reqId = rec["reqId"] ? pc.magenta(String(rec["reqId"]).slice(0, 8)) + " " : "";
46
- const extra = Object.entries(rec).filter(([k]) => !OMIT.has(k));
47
- const err = rec["err"];
48
- const fields = extra.filter(([k]) => k !== "err").map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
49
- out.write(
50
- `${pc.dim(time)} ${level} ${worker}${reqId}${String(rec["msg"] ?? "")}` + (fields ? " " + pc.dim(fields) : "") + (err?.stack ? "\n" + pc.red(err.stack) : "") + "\n"
51
- );
52
- }
53
- };
54
- }
55
- function workerLabel() {
56
- return cluster.isWorker ? `w${cluster.worker?.id ?? "?"}` : "primary";
57
- }
58
- function build(config) {
59
- if (config === false) return pino({ level: "silent" });
60
- const opts = config ?? {};
61
- const pretty = opts.pretty ?? (process.env["NODE_ENV"] !== "production" && process.stdout.isTTY === true);
62
- const base = { worker: workerLabel() };
63
- const level = opts.level ?? "info";
64
- return pretty ? pino({ level, base, errorKey: "err" }, prettyStream()) : pino({ level, base, errorKey: "err", timestamp: pino.stdTimeFunctions.isoTime });
65
- }
66
- var rootLogger = build(void 0);
67
- var logRequests = true;
68
- function configureLogger(config) {
69
- rootLogger = build(config);
70
- logRequests = config !== false && (config?.requests ?? true);
71
- }
72
- function getLogger() {
73
- return getRequestContext()?.log ?? rootLogger;
74
- }
75
- var logger = new Proxy({}, {
76
- get(_t, prop) {
77
- const target = getLogger();
78
- const value = target[prop];
79
- return typeof value === "function" ? value.bind(target) : value;
80
- }
81
- });
82
- var SAFE_REQUEST_ID = /^[\w.:-]{1,128}$/;
83
- function requestLogger() {
84
- return (req, res, next) => {
85
- const incoming = req.get("x-request-id");
86
- const id = incoming && SAFE_REQUEST_ID.test(incoming) ? incoming : randomUUID();
87
- const log = rootLogger.child({ reqId: id });
88
- req.id = id;
89
- req.log = log;
90
- res.setHeader("X-Request-Id", id);
91
- const ctx = getRequestContext();
92
- if (ctx) {
93
- ctx.requestId = id;
94
- ctx.log = log;
95
- }
96
- if (logRequests) {
97
- const start = process.hrtime.bigint();
98
- res.on("finish", () => {
99
- const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
100
- const status = res.statusCode;
101
- const line = {
102
- method: req.method,
103
- url: req.originalUrl,
104
- status,
105
- durationMs: Math.round(durationMs * 10) / 10
106
- };
107
- const msg = `${req.method} ${req.originalUrl} ${status}`;
108
- if (status >= 500) log.error(line, msg);
109
- else if (status >= 400) log.warn(line, msg);
110
- else log.info(line, msg);
111
- });
112
- }
113
- next();
114
- };
115
- }
116
-
117
- export {
118
- runWithContext,
119
- getRequestContext,
120
- setCurrentUser,
121
- getCurrentUser,
122
- configureLogger,
123
- getLogger,
124
- logger,
125
- requestLogger
126
- };
127
- //# sourceMappingURL=chunk-277BSYVH.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/context.ts","../src/logger.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { Logger } from 'pino';\n\nexport interface RequestContext {\n user?: Record<string, unknown> | undefined;\n requestId?: string;\n log?: Logger;\n /** Model operations run so far in this request, by `Model.op` (N+1 detection). */\n queryCounts?: Map<string, number>;\n}\n\nconst storage = new AsyncLocalStorage<RequestContext>();\n\n// Wraps one request's lifecycle in an AsyncLocalStorage context. Node propagates\n// the store through the async chain the callback initiates (awaits, .then, etc.),\n// so anything running as part of the same request — including a `$currentUser`\n// default resolved deep inside a mongoose `.create()` call — can read it back.\nexport function runWithContext<T>(ctx: RequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getRequestContext(): RequestContext | undefined {\n return storage.getStore();\n}\n\nexport function setCurrentUser(user: Record<string, unknown> | undefined): void {\n const store = storage.getStore();\n if (store) store.user = user;\n}\n\nexport function getCurrentUser(): Record<string, unknown> | undefined {\n return storage.getStore()?.user;\n}\n","import cluster from 'node:cluster';\nimport { randomUUID } from 'node:crypto';\nimport type { RequestHandler } from 'express';\nimport pc from 'picocolors';\nimport { pino, type Logger, type DestinationStream } from 'pino';\nimport type { LoggingConfig } from './types.js';\nimport { getRequestContext } from './context.js';\n\nexport type { Logger };\n\nconst LEVEL_LABELS: Record<number, string> = {\n 10: pc.gray('TRACE'),\n 20: pc.blue('DEBUG'),\n 30: pc.green('INFO '),\n 40: pc.yellow('WARN '),\n 50: pc.red('ERROR'),\n 60: pc.bgRed('FATAL'),\n};\n\nconst OMIT = new Set(['level', 'time', 'msg', 'pid', 'hostname', 'worker', 'reqId']);\n\n// Dev-friendly one-line renderer, so readable output doesn't need pino-pretty or a\n// transport worker thread: `12:00:01 INFO [w2] a1b2c3d4 GET /users 200 (3ms)`.\nfunction prettyStream(out: NodeJS.WritableStream = process.stdout): DestinationStream {\n return {\n write(line: string) {\n let rec: Record<string, unknown>;\n try {\n rec = JSON.parse(line) as Record<string, unknown>;\n } catch {\n out.write(line);\n return;\n }\n const time = new Date(rec['time'] as number).toTimeString().slice(0, 8);\n const level = LEVEL_LABELS[rec['level'] as number] ?? String(rec['level']);\n const worker = rec['worker'] !== undefined ? pc.dim(`[${String(rec['worker'])}] `) : '';\n const reqId = rec['reqId'] ? pc.magenta(String(rec['reqId']).slice(0, 8)) + ' ' : '';\n const extra = Object.entries(rec).filter(([k]) => !OMIT.has(k));\n const err = rec['err'] as { stack?: string } | undefined;\n const fields = extra\n .filter(([k]) => k !== 'err')\n .map(([k, v]) => `${k}=${typeof v === 'string' ? v : JSON.stringify(v)}`)\n .join(' ');\n out.write(\n `${pc.dim(time)} ${level} ${worker}${reqId}${String(rec['msg'] ?? '')}` +\n (fields ? ' ' + pc.dim(fields) : '') +\n (err?.stack ? '\\n' + pc.red(err.stack) : '') +\n '\\n',\n );\n },\n };\n}\n\nfunction workerLabel(): string {\n return cluster.isWorker ? `w${cluster.worker?.id ?? '?'}` : 'primary';\n}\n\nfunction build(config: LoggingConfig | false | undefined): Logger {\n if (config === false) return pino({ level: 'silent' });\n const opts = config ?? {};\n const pretty =\n opts.pretty ?? (process.env['NODE_ENV'] !== 'production' && process.stdout.isTTY === true);\n const base = { worker: workerLabel() };\n const level = opts.level ?? 'info';\n return pretty\n ? pino({ level, base, errorKey: 'err' }, prettyStream())\n : pino({ level, base, errorKey: 'err', timestamp: pino.stdTimeFunctions.isoTime });\n}\n\nlet rootLogger: Logger = build(undefined);\nlet logRequests = true;\n\n/** Called by ignite() during Pre-Flight; before that the defaults apply. */\nexport function configureLogger(config: LoggingConfig | false | undefined): void {\n rootLogger = build(config);\n logRequests = config !== false && (config?.requests ?? true);\n}\n\n/**\n * The logger for the current scope: inside a request it is a child carrying that\n * request's `reqId`, so everything logged while handling it can be correlated;\n * elsewhere (startup, task handlers, timers) it is the root logger.\n */\nexport function getLogger(): Logger {\n return getRequestContext()?.log ?? rootLogger;\n}\n\n/** Root logger proxy — always reflects the latest configureLogger() call. */\nexport const logger: Logger = new Proxy({} as Logger, {\n get(_t, prop) {\n const target = getLogger() as unknown as Record<PropertyKey, unknown>;\n const value = target[prop];\n return typeof value === 'function'\n ? (value as (...a: unknown[]) => unknown).bind(target)\n : value;\n },\n});\n\nconst SAFE_REQUEST_ID = /^[\\w.:-]{1,128}$/;\n\n/**\n * Assigns the request ID (trusting a well-formed incoming `X-Request-Id`, e.g. from\n * a load balancer), echoes it back, attaches `req.id` / `req.log`, and logs one\n * line per completed request. Must run inside the request's context.\n */\nexport function requestLogger(): RequestHandler {\n return (req, res, next) => {\n const incoming = req.get('x-request-id');\n const id = incoming && SAFE_REQUEST_ID.test(incoming) ? incoming : randomUUID();\n const log = rootLogger.child({ reqId: id });\n\n req.id = id;\n req.log = log;\n res.setHeader('X-Request-Id', id);\n const ctx = getRequestContext();\n if (ctx) {\n ctx.requestId = id;\n ctx.log = log;\n }\n\n if (logRequests) {\n const start = process.hrtime.bigint();\n res.on('finish', () => {\n const durationMs = Number(process.hrtime.bigint() - start) / 1e6;\n const status = res.statusCode;\n const line = {\n method: req.method,\n url: req.originalUrl,\n status,\n durationMs: Math.round(durationMs * 10) / 10,\n };\n const msg = `${req.method} ${req.originalUrl} ${status}`;\n if (status >= 500) log.error(line, msg);\n else if (status >= 400) log.warn(line, msg);\n else log.info(line, msg);\n });\n }\n next();\n };\n}\n\ndeclare module 'express-serve-static-core' {\n interface Request {\n /** Request ID — the incoming `X-Request-Id` if well-formed, else a UUID. */\n id: string;\n /** Logger bound to this request's ID. */\n log: Logger;\n }\n}\n"],"mappings":";AAAA,SAAS,yBAAyB;AAWlC,IAAM,UAAU,IAAI,kBAAkC;AAM/C,SAAS,eAAkB,KAAqB,IAAgB;AACrE,SAAO,QAAQ,IAAI,KAAK,EAAE;AAC5B;AAEO,SAAS,oBAAgD;AAC9D,SAAO,QAAQ,SAAS;AAC1B;AAEO,SAAS,eAAe,MAAiD;AAC9E,QAAM,QAAQ,QAAQ,SAAS;AAC/B,MAAI,MAAO,OAAM,OAAO;AAC1B;AAEO,SAAS,iBAAsD;AACpE,SAAO,QAAQ,SAAS,GAAG;AAC7B;;;AChCA,OAAO,aAAa;AACpB,SAAS,kBAAkB;AAE3B,OAAO,QAAQ;AACf,SAAS,YAAiD;AAM1D,IAAM,eAAuC;AAAA,EAC3C,IAAI,GAAG,KAAK,OAAO;AAAA,EACnB,IAAI,GAAG,KAAK,OAAO;AAAA,EACnB,IAAI,GAAG,MAAM,OAAO;AAAA,EACpB,IAAI,GAAG,OAAO,OAAO;AAAA,EACrB,IAAI,GAAG,IAAI,OAAO;AAAA,EAClB,IAAI,GAAG,MAAM,OAAO;AACtB;AAEA,IAAM,OAAO,oBAAI,IAAI,CAAC,SAAS,QAAQ,OAAO,OAAO,YAAY,UAAU,OAAO,CAAC;AAInF,SAAS,aAAa,MAA6B,QAAQ,QAA2B;AACpF,SAAO;AAAA,IACL,MAAM,MAAc;AAClB,UAAI;AACJ,UAAI;AACF,cAAM,KAAK,MAAM,IAAI;AAAA,MACvB,QAAQ;AACN,YAAI,MAAM,IAAI;AACd;AAAA,MACF;AACA,YAAM,OAAO,IAAI,KAAK,IAAI,MAAM,CAAW,EAAE,aAAa,EAAE,MAAM,GAAG,CAAC;AACtE,YAAM,QAAQ,aAAa,IAAI,OAAO,CAAW,KAAK,OAAO,IAAI,OAAO,CAAC;AACzE,YAAM,SAAS,IAAI,QAAQ,MAAM,SAAY,GAAG,IAAI,IAAI,OAAO,IAAI,QAAQ,CAAC,CAAC,IAAI,IAAI;AACrF,YAAM,QAAQ,IAAI,OAAO,IAAI,GAAG,QAAQ,OAAO,IAAI,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,IAAI,MAAM;AAClF,YAAM,QAAQ,OAAO,QAAQ,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC,CAAC;AAC9D,YAAM,MAAM,IAAI,KAAK;AACrB,YAAM,SAAS,MACZ,OAAO,CAAC,CAAC,CAAC,MAAM,MAAM,KAAK,EAC3B,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,MAAM,WAAW,IAAI,KAAK,UAAU,CAAC,CAAC,EAAE,EACvE,KAAK,GAAG;AACX,UAAI;AAAA,QACF,GAAG,GAAG,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,MAAM,GAAG,KAAK,GAAG,OAAO,IAAI,KAAK,KAAK,EAAE,CAAC,MAClE,SAAS,MAAM,GAAG,IAAI,MAAM,IAAI,OAChC,KAAK,QAAQ,OAAO,GAAG,IAAI,IAAI,KAAK,IAAI,MACzC;AAAA,MACJ;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,cAAsB;AAC7B,SAAO,QAAQ,WAAW,IAAI,QAAQ,QAAQ,MAAM,GAAG,KAAK;AAC9D;AAEA,SAAS,MAAM,QAAmD;AAChE,MAAI,WAAW,MAAO,QAAO,KAAK,EAAE,OAAO,SAAS,CAAC;AACrD,QAAM,OAAO,UAAU,CAAC;AACxB,QAAM,SACJ,KAAK,WAAW,QAAQ,IAAI,UAAU,MAAM,gBAAgB,QAAQ,OAAO,UAAU;AACvF,QAAM,OAAO,EAAE,QAAQ,YAAY,EAAE;AACrC,QAAM,QAAQ,KAAK,SAAS;AAC5B,SAAO,SACH,KAAK,EAAE,OAAO,MAAM,UAAU,MAAM,GAAG,aAAa,CAAC,IACrD,KAAK,EAAE,OAAO,MAAM,UAAU,OAAO,WAAW,KAAK,iBAAiB,QAAQ,CAAC;AACrF;AAEA,IAAI,aAAqB,MAAM,MAAS;AACxC,IAAI,cAAc;AAGX,SAAS,gBAAgB,QAAiD;AAC/E,eAAa,MAAM,MAAM;AACzB,gBAAc,WAAW,UAAU,QAAQ,YAAY;AACzD;AAOO,SAAS,YAAoB;AAClC,SAAO,kBAAkB,GAAG,OAAO;AACrC;AAGO,IAAM,SAAiB,IAAI,MAAM,CAAC,GAAa;AAAA,EACpD,IAAI,IAAI,MAAM;AACZ,UAAM,SAAS,UAAU;AACzB,UAAM,QAAQ,OAAO,IAAI;AACzB,WAAO,OAAO,UAAU,aACnB,MAAuC,KAAK,MAAM,IACnD;AAAA,EACN;AACF,CAAC;AAED,IAAM,kBAAkB;AAOjB,SAAS,gBAAgC;AAC9C,SAAO,CAAC,KAAK,KAAK,SAAS;AACzB,UAAM,WAAW,IAAI,IAAI,cAAc;AACvC,UAAM,KAAK,YAAY,gBAAgB,KAAK,QAAQ,IAAI,WAAW,WAAW;AAC9E,UAAM,MAAM,WAAW,MAAM,EAAE,OAAO,GAAG,CAAC;AAE1C,QAAI,KAAK;AACT,QAAI,MAAM;AACV,QAAI,UAAU,gBAAgB,EAAE;AAChC,UAAM,MAAM,kBAAkB;AAC9B,QAAI,KAAK;AACP,UAAI,YAAY;AAChB,UAAI,MAAM;AAAA,IACZ;AAEA,QAAI,aAAa;AACf,YAAM,QAAQ,QAAQ,OAAO,OAAO;AACpC,UAAI,GAAG,UAAU,MAAM;AACrB,cAAM,aAAa,OAAO,QAAQ,OAAO,OAAO,IAAI,KAAK,IAAI;AAC7D,cAAM,SAAS,IAAI;AACnB,cAAM,OAAO;AAAA,UACX,QAAQ,IAAI;AAAA,UACZ,KAAK,IAAI;AAAA,UACT;AAAA,UACA,YAAY,KAAK,MAAM,aAAa,EAAE,IAAI;AAAA,QAC5C;AACA,cAAM,MAAM,GAAG,IAAI,MAAM,IAAI,IAAI,WAAW,IAAI,MAAM;AACtD,YAAI,UAAU,IAAK,KAAI,MAAM,MAAM,GAAG;AAAA,iBAC7B,UAAU,IAAK,KAAI,KAAK,MAAM,GAAG;AAAA,YACrC,KAAI,KAAK,MAAM,GAAG;AAAA,MACzB,CAAC;AAAA,IACH;AACA,SAAK;AAAA,EACP;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-7YEX4MQV.cjs","../src/tasks/thread-runner.ts"],"names":[],"mappings":"AAAA;ACAA,gDAA6D;AAI7D,GAAA,CAAI,CAAC,4BAAA,EAAc;AACjB,EAAA,MAAM,EAAE,WAAA,EAAa,QAAQ,EAAA,EAAI,0BAAA;AAEjC,EAAA,CAAC,MAAA,CAAA,EAAA,GAAY;AACX,IAAA,IAAI;AACF,MAAA,MAAM,IAAA,EAAO,MAAM,4DAAA,CAAO,WAAA,GAAA;AAC1B,MAAA,MAAM,IAAA,EAAM,GAAA,CAAI,SAAS,CAAA;AACzB,MAAA,GAAA,CAAI,CAAC,IAAA,GAAO,OAAO,GAAA,CAAI,QAAA,IAAY,UAAA,EAAY;AAC7C,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,6CAAA,EAAgD,WAAW,CAAA,CAAA;AAC7E,MAAA;AACyB,MAAA;AACW,sBAAA;AACxB,IAAA;AAC6C,sBAAA;AAC3D,IAAA;AACC,EAAA;AACL;AAGkF;AACxC,EAAA;AACoC,IAAA;AACrC,MAAA;AACpC,IAAA;AAE8D,IAAA;AACzC,MAAA;AACoC,MAAA;AACzD,IAAA;AAEwB,IAAA;AACG,IAAA;AACgD,MAAA;AAC3E,IAAA;AACF,EAAA;AACH;ADNoF;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-7YEX4MQV.cjs","sourcesContent":[null,"import { Worker, workerData, parentPort, isMainThread } from 'node:worker_threads';\nimport type { TaskDefinition } from '../types.js';\n\n// ── Worker-thread side ────────────────────────────────────────────────────────\nif (!isMainThread) {\n const { handlerPath, payload } = workerData as { handlerPath: string; payload: unknown };\n\n (async () => {\n try {\n const mod = (await import(handlerPath)) as Record<string, unknown>;\n const def = mod['default'] as TaskDefinition | undefined;\n if (!def || typeof def.handler !== 'function') {\n throw new Error(`[EFC] Thread runner: no valid task export in ${handlerPath}`);\n }\n await def.handler(payload);\n parentPort?.postMessage({ ok: true });\n } catch (err) {\n parentPort?.postMessage({ ok: false, error: String(err) });\n }\n })();\n}\n\n// ── Main-thread side ──────────────────────────────────────────────────────────\nexport function runInThread(handlerPath: string, payload: unknown): Promise<void> {\n return new Promise((resolve, reject) => {\n const worker = new Worker(new URL('./thread-runner.js', import.meta.url), {\n workerData: { handlerPath, payload },\n });\n\n worker.on('message', (msg: { ok: boolean; error?: string }) => {\n if (msg.ok) resolve();\n else reject(new Error(msg.error ?? 'Thread task failed'));\n });\n\n worker.on('error', reject);\n worker.on('exit', (code) => {\n if (code !== 0) reject(new Error(`Thread worker exited with code ${code}`));\n });\n });\n}\n"]}