express-file-cluster 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/dist/auth/index.cjs +7 -6
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.d.cts +1 -1
  4. package/dist/auth/index.d.ts +1 -1
  5. package/dist/auth/index.js +5 -5
  6. package/dist/{chunk-R52CUEGT.js → chunk-3SWI46YK.js} +2 -2
  7. package/dist/{chunk-DCJOWFVD.cjs → chunk-4GHK27JA.cjs} +3 -3
  8. package/dist/{chunk-DCJOWFVD.cjs.map → chunk-4GHK27JA.cjs.map} +1 -1
  9. package/dist/{chunk-NI2BNGGV.js → chunk-5LPRKZPB.js} +2 -2
  10. package/dist/chunk-74BSJXWD.cjs +220 -0
  11. package/dist/chunk-74BSJXWD.cjs.map +1 -0
  12. package/dist/{chunk-7KO4DJRJ.cjs → chunk-7BC3AN7R.cjs} +14 -14
  13. package/dist/{chunk-7KO4DJRJ.cjs.map → chunk-7BC3AN7R.cjs.map} +1 -1
  14. package/dist/chunk-AGOYTFRO.cjs +42 -0
  15. package/dist/chunk-AGOYTFRO.cjs.map +1 -0
  16. package/dist/{chunk-RAB44UGX.js → chunk-B6MB6HEG.js} +1 -1
  17. package/dist/{chunk-PGJQK36V.js → chunk-BG4A7Z32.js} +7 -5
  18. package/dist/{chunk-PGJQK36V.js.map → chunk-BG4A7Z32.js.map} +1 -1
  19. package/dist/{chunk-ATVD2HGC.js → chunk-C2FOZ7ME.js} +4 -4
  20. package/dist/chunk-CGY7JU4Y.cjs +8 -0
  21. package/dist/chunk-CGY7JU4Y.cjs.map +1 -0
  22. package/dist/{chunk-EGSSZUVO.js → chunk-DN4TCGYB.js} +38 -11
  23. package/dist/chunk-DN4TCGYB.js.map +1 -0
  24. package/dist/{chunk-GBI77W5T.cjs → chunk-H2PVWCWC.cjs} +1 -1
  25. package/dist/{chunk-GBI77W5T.cjs.map → chunk-H2PVWCWC.cjs.map} +1 -1
  26. package/dist/{chunk-NKLOE4AK.cjs → chunk-IUZ6A7PB.cjs} +20 -53
  27. package/dist/chunk-IUZ6A7PB.cjs.map +1 -0
  28. package/dist/{chunk-DUADUR6R.cjs → chunk-JP36TLL4.cjs} +171 -14
  29. package/dist/chunk-JP36TLL4.cjs.map +1 -0
  30. package/dist/chunk-KLWL7XSC.js +220 -0
  31. package/dist/chunk-KLWL7XSC.js.map +1 -0
  32. package/dist/{chunk-4DOHQU6I.cjs → chunk-M53GODCX.cjs} +39 -12
  33. package/dist/chunk-M53GODCX.cjs.map +1 -0
  34. package/dist/{chunk-R4XO4SVM.js → chunk-MUVO7MGS.js} +4 -4
  35. package/dist/{chunk-HBCY7ILD.cjs → chunk-R2K7AFIB.cjs} +97 -95
  36. package/dist/chunk-R2K7AFIB.cjs.map +1 -0
  37. package/dist/{chunk-QDEDOHP7.js → chunk-RETV3GKE.js} +9 -42
  38. package/dist/chunk-RETV3GKE.js.map +1 -0
  39. package/dist/{chunk-WBLUGOAG.cjs → chunk-RPL2IFWK.cjs} +8 -5
  40. package/dist/chunk-RPL2IFWK.cjs.map +1 -0
  41. package/dist/{chunk-YK4ZM3CA.cjs → chunk-TBIVIR6L.cjs} +15 -15
  42. package/dist/{chunk-YK4ZM3CA.cjs.map → chunk-TBIVIR6L.cjs.map} +1 -1
  43. package/dist/{chunk-73XJUT2S.js → chunk-V73R76I4.js} +162 -5
  44. package/dist/chunk-V73R76I4.js.map +1 -0
  45. package/dist/chunk-XPY5TQDK.js +42 -0
  46. package/dist/chunk-XPY5TQDK.js.map +1 -0
  47. package/dist/{chunk-KFVFP2Q7.cjs → chunk-Y4NKIXUL.cjs} +70 -55
  48. package/dist/chunk-Y4NKIXUL.cjs.map +1 -0
  49. package/dist/{chunk-7KC2H76D.js → chunk-Y75V5FCU.js} +62 -47
  50. package/dist/chunk-Y75V5FCU.js.map +1 -0
  51. package/dist/cli/db-runner.cjs +81 -42
  52. package/dist/cli/db-runner.cjs.map +1 -1
  53. package/dist/cli/db-runner.js +54 -16
  54. package/dist/cli/db-runner.js.map +1 -1
  55. package/dist/cli/index.cjs +23 -25
  56. package/dist/cli/index.cjs.map +1 -1
  57. package/dist/cli/index.js +12 -17
  58. package/dist/cli/index.js.map +1 -1
  59. package/dist/docs/api-reference/auth.md +23 -0
  60. package/dist/docs/api-reference/compose.md +1 -1
  61. package/dist/docs/api-reference/db.md +8 -0
  62. package/dist/docs/api-reference/ignite.md +4 -1
  63. package/dist/docs/api-reference/testing.md +26 -0
  64. package/dist/docs/cli/add.md +2 -2
  65. package/dist/docs/core-concepts/file-based-routing.md +2 -0
  66. package/dist/docs/core-concepts/middleware.md +2 -2
  67. package/dist/docs/getting-started/index.md +4 -0
  68. package/dist/docs/guides/authentication.md +33 -0
  69. package/dist/docs/guides/caching.md +2 -0
  70. package/dist/docs/guides/database.md +15 -0
  71. package/dist/docs/guides/environment-variables.md +6 -0
  72. package/dist/docs/guides/generated-portals.md +3 -1
  73. package/dist/docs/guides/logging.md +17 -0
  74. package/dist/docs/guides/migrations.md +4 -2
  75. package/dist/docs/guides/testing.md +31 -0
  76. package/dist/docs/index.md +2 -1
  77. package/dist/docs/skills/SKILL.md +5 -1
  78. package/dist/docs/skills/api-surface.md +20 -4
  79. package/dist/docs/skills/auth-internals.md +14 -1
  80. package/dist/docs/skills/pre-flight.md +6 -0
  81. package/dist/docs/skills/routing-rules.md +1 -1
  82. package/dist/docs/skills/what-not-to-invent.md +9 -1
  83. package/dist/docs/versioning.md +1 -1
  84. package/dist/index.cjs +75 -264
  85. package/dist/index.cjs.map +1 -1
  86. package/dist/index.d.cts +27 -3
  87. package/dist/index.d.ts +27 -3
  88. package/dist/index.js +28 -218
  89. package/dist/index.js.map +1 -1
  90. package/dist/pgboss-backend-4X2YT4RB.js +14 -0
  91. package/dist/pgboss-backend-UXQ3O2WT.cjs +15 -0
  92. package/dist/pgboss-backend-UXQ3O2WT.cjs.map +1 -0
  93. package/dist/registry/index.json +27 -3
  94. package/dist/registry/js-mongo/account-security.json +1 -1
  95. package/dist/registry/js-mongo/admin-users.json +1 -1
  96. package/dist/registry/js-mongo/auth.json +1 -1
  97. package/dist/registry/js-mongo/auth@apple.json +1 -1
  98. package/dist/registry/js-mongo/auth@google.json +1 -1
  99. package/dist/registry/js-mongo/forgot-password.json +1 -1
  100. package/dist/registry/js-mongo/user-profile.json +1 -1
  101. package/dist/registry/js-mongo-collection/account-security.json +1 -1
  102. package/dist/registry/js-mongo-collection/admin-users.json +1 -1
  103. package/dist/registry/js-mongo-collection/auth.json +1 -1
  104. package/dist/registry/js-mongo-collection/auth@apple.json +1 -1
  105. package/dist/registry/js-mongo-collection/auth@google.json +1 -1
  106. package/dist/registry/js-mongo-collection/forgot-password.json +1 -1
  107. package/dist/registry/js-mongo-collection/user-profile.json +1 -1
  108. package/dist/registry/js-pg-model/account-security.json +1 -1
  109. package/dist/registry/js-pg-model/admin-users.json +1 -1
  110. package/dist/registry/js-pg-model/auth.json +1 -1
  111. package/dist/registry/js-pg-model/auth@apple.json +1 -1
  112. package/dist/registry/js-pg-model/auth@google.json +1 -1
  113. package/dist/registry/js-pg-model/forgot-password.json +1 -1
  114. package/dist/registry/js-pg-model/user-profile.json +1 -1
  115. package/dist/registry/js-pg-table/account-security.json +1 -1
  116. package/dist/registry/js-pg-table/admin-users.json +1 -1
  117. package/dist/registry/js-pg-table/auth.json +1 -1
  118. package/dist/registry/js-pg-table/auth@apple.json +1 -1
  119. package/dist/registry/js-pg-table/auth@google.json +1 -1
  120. package/dist/registry/js-pg-table/forgot-password.json +1 -1
  121. package/dist/registry/js-pg-table/user-profile.json +1 -1
  122. package/dist/registry/ts-mongo/account-security.json +1 -1
  123. package/dist/registry/ts-mongo/admin-users.json +1 -1
  124. package/dist/registry/ts-mongo/auth.json +1 -1
  125. package/dist/registry/ts-mongo/auth@apple.json +1 -1
  126. package/dist/registry/ts-mongo/auth@google.json +1 -1
  127. package/dist/registry/ts-mongo/forgot-password.json +1 -1
  128. package/dist/registry/ts-mongo/user-profile.json +1 -1
  129. package/dist/registry/ts-mongo-collection/account-security.json +1 -1
  130. package/dist/registry/ts-mongo-collection/admin-users.json +1 -1
  131. package/dist/registry/ts-mongo-collection/auth.json +1 -1
  132. package/dist/registry/ts-mongo-collection/auth@apple.json +1 -1
  133. package/dist/registry/ts-mongo-collection/auth@google.json +1 -1
  134. package/dist/registry/ts-mongo-collection/forgot-password.json +1 -1
  135. package/dist/registry/ts-mongo-collection/user-profile.json +1 -1
  136. package/dist/registry/ts-pg-model/account-security.json +1 -1
  137. package/dist/registry/ts-pg-model/admin-users.json +1 -1
  138. package/dist/registry/ts-pg-model/auth.json +1 -1
  139. package/dist/registry/ts-pg-model/auth@apple.json +1 -1
  140. package/dist/registry/ts-pg-model/auth@google.json +1 -1
  141. package/dist/registry/ts-pg-model/forgot-password.json +1 -1
  142. package/dist/registry/ts-pg-model/user-profile.json +1 -1
  143. package/dist/registry/ts-pg-table/account-security.json +1 -1
  144. package/dist/registry/ts-pg-table/admin-users.json +1 -1
  145. package/dist/registry/ts-pg-table/auth.json +1 -1
  146. package/dist/registry/ts-pg-table/auth@apple.json +1 -1
  147. package/dist/registry/ts-pg-table/auth@google.json +1 -1
  148. package/dist/registry/ts-pg-table/forgot-password.json +1 -1
  149. package/dist/registry/ts-pg-table/user-profile.json +1 -1
  150. package/dist/tasks/index.cjs +3 -2
  151. package/dist/tasks/index.cjs.map +1 -1
  152. package/dist/tasks/index.d.cts +1 -1
  153. package/dist/tasks/index.d.ts +1 -1
  154. package/dist/tasks/index.js +1 -1
  155. package/dist/testing-cjs.cjs +5 -0
  156. package/dist/testing.cjs +59 -0
  157. package/dist/testing.cjs.map +1 -0
  158. package/dist/testing.d.cts +27 -0
  159. package/dist/testing.d.ts +27 -0
  160. package/dist/testing.js +58 -0
  161. package/dist/testing.js.map +1 -0
  162. package/dist/thread-runner.cjs +4 -3
  163. package/dist/thread-runner.cjs.map +1 -1
  164. package/dist/thread-runner.js +2 -2
  165. package/dist/{types-Bnxvj3l0.d.ts → types-CPMFTVXm.d.cts} +8 -0
  166. package/dist/{types-Bnxvj3l0.d.cts → types-CPMFTVXm.d.ts} +8 -0
  167. package/package.json +6 -1
  168. package/dist/chunk-4DOHQU6I.cjs.map +0 -1
  169. package/dist/chunk-73XJUT2S.js.map +0 -1
  170. package/dist/chunk-7KC2H76D.js.map +0 -1
  171. package/dist/chunk-DUADUR6R.cjs.map +0 -1
  172. package/dist/chunk-EGSSZUVO.js.map +0 -1
  173. package/dist/chunk-HBCY7ILD.cjs.map +0 -1
  174. package/dist/chunk-KFVFP2Q7.cjs.map +0 -1
  175. package/dist/chunk-NKLOE4AK.cjs.map +0 -1
  176. package/dist/chunk-QDEDOHP7.js.map +0 -1
  177. package/dist/chunk-WBLUGOAG.cjs.map +0 -1
  178. package/dist/pgboss-backend-FW42SBSM.js +0 -14
  179. package/dist/pgboss-backend-RVHUBJTU.cjs +0 -14
  180. package/dist/pgboss-backend-RVHUBJTU.cjs.map +0 -1
  181. /package/dist/{chunk-R52CUEGT.js.map → chunk-3SWI46YK.js.map} +0 -0
  182. /package/dist/{chunk-NI2BNGGV.js.map → chunk-5LPRKZPB.js.map} +0 -0
  183. /package/dist/{chunk-RAB44UGX.js.map → chunk-B6MB6HEG.js.map} +0 -0
  184. /package/dist/{chunk-ATVD2HGC.js.map → chunk-C2FOZ7ME.js.map} +0 -0
  185. /package/dist/{chunk-R4XO4SVM.js.map → chunk-MUVO7MGS.js.map} +0 -0
  186. /package/dist/{pgboss-backend-FW42SBSM.js.map → pgboss-backend-4X2YT4RB.js.map} +0 -0
@@ -1 +1 @@
1
- {"name":"user-profile","files":[{"path":"src/api/user/profile.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nexport const meta = {\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, res) => {\n const { id } = req.user;\n const user = await User.findById(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, res) => {\n const { id } = req.user;\n const { name, email } = req.body;\n const updated = await User.findByIdAndUpdate(id, { name, email }, { returnDocument: 'after' });\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":[]}
1
+ {"name":"user-profile","files":[{"path":"src/api/user/profile.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nexport const meta = {\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, res) => {\n const { id } = req.user;\n const user = await User.findById(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, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.user;\n const { name, email } = req.body ?? {};\n if ((name !== undefined && typeof name !== 'string') || (email !== undefined && typeof email !== 'string')) return res.status(400).json({ error: 'name and email must be strings' });\n const existing = await User.findById(id);\n if (!existing) return res.status(404).json({ error: 'User not found' });\n if (email !== undefined && email !== existing.email && existing.twoFactorEnabled && existing.twoFactorMethod === 'email') return res.status(409).json({ error: 'Disable email 2FA before changing the email address' });\n const updated = await User.findByIdAndUpdate(id, { name, email }, { returnDocument: 'after' });\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, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = updated;\n res.json({ message: 'Profile updated', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Disable 2FA for the authenticated user.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA disabled' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify code and disable 2FA\n res.json({ message: '2FA disabled' });\n};\n"},{"path":"src/api/auth/2fa/setup.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Generate a TOTP secret and QR code to set up 2FA.',\n response: { status: 200, body: { qrCode: 'otpauth://totp/...', secret: 'BASE32SECRET' } },\n },\n POST: {\n description: 'Confirm a TOTP code to enable 2FA for the authenticated user.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA enabled' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: generate TOTP secret and return QR code URL\n res.json({ qrCode: 'otpauth://totp/...', secret: 'BASE32SECRET' });\n};\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify TOTP code and enable 2FA\n res.json({ message: '2FA enabled' });\n};\n"},{"path":"src/api/auth/2fa/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Verify a TOTP code during login.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA verified' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify TOTP code\n res.json({ message: '2FA verified' });\n};\n"},{"path":"src/api/auth/change-password.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Change password for the authenticated user.',\n request: { body: { oldPassword: 'current', newPassword: 'newpassword' } },\n response: { status: 200, body: { message: 'Password changed successfully' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req, res) => {\n const { oldPassword, newPassword } = req.body;\n if (!oldPassword || !newPassword) return res.status(400).json({ error: 'oldPassword and newPassword are required' });\n // TODO: verify old password, hash and update new password, then sign out other devices:\n // await revokeAllSessions(req.user.id) (import from 'express-file-cluster/auth')\n res.json({ message: 'Password changed successfully' });\n};\n"},{"path":"src/api/auth/refresh.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Refresh the JWT using the refresh-token cookie and issue a new access token.',\n response: { status: 200, body: { message: 'Token refreshed' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nexport const POST = async (req, res) => {\n const token = req.cookies?.efc_refresh_token || req.body?.refreshToken;\n if (!token) return res.status(401).json({ error: 'Refresh token required' });\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') return res.status(400).json({ error: 'Invalid refresh token' });\n\n const user = await User.findOne({ refreshToken: token });\n const admin = user ? null : await Admin.findOne({ refreshToken: token });\n const account = user || admin;\n\n if (!account || !account.refreshTokenExpiry || new Date(account.refreshTokenExpiry) < new Date()) {\n return res.status(401).json({ error: 'Invalid or expired refresh token' });\n }\n if (account.isActive === false) return res.status(403).json({ error: 'Account suspended' });\n\n const newRefreshToken = crypto.randomBytes(40).toString('hex');\n const refreshTokenExpiry = new Date(Date.now() + REFRESH_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { refreshToken: newRefreshToken, refreshTokenExpiry });\n else if (admin) await Admin.update(admin.id, { refreshToken: newRefreshToken, refreshTokenExpiry });\n\n res.cookie('efc_refresh_token', newRefreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n\n const accessToken = await issueToken(res, { id: account.id, role: account.role, email: account.email });\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({\n message: 'Token refreshed',\n ...(accessToken ? { token: accessToken, refreshToken: newRefreshToken } : {}),\n });\n};\n"},{"path":"src/api/auth/sessions/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n DELETE: {\n description: 'Revoke a single active session by ID.',\n request: { params: { id: 'sess_01HXZ' } },\n response: { status: 200, body: { message: 'Session sess_01HXZ revoked' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n // TODO: revoke session by id\n res.json({ message: `Session ${id} revoked` });\n};\n"},{"path":"src/api/auth/sessions/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'List all active sessions for the authenticated user.',\n response: { status: 200, body: { sessions: [] } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: fetch sessions for req.user.id\n res.json({ sessions: [] });\n};\n"},{"path":"src/model/Session.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Session = defineModel('Session', {\n userId: { type: 'string', required: true },\n token: { type: 'string', required: true, unique: true },\n ip: { type: 'string', required: true },\n userAgent: { type: 'string', required: true },\n expiresAt: { type: 'date', required: true },\n isActive: { type: 'boolean', default: true },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.js","content":"import { requireAuth, getCurrentUser, verifyPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { HttpError, rateLimit } from 'express-file-cluster';\nimport { User } from '../../../model/User.js';\nimport { Admin } from '../../../model/Admin.js';\nimport { newSecret, sealSecret, openSecret, codeStep, updateSecurity, acceptTwoFactor, allowedMethods, sendEmailCode, consumeEmailCode } from '../../../lib/two-factor.js';\n\nexport const middlewares = [requireAuth, rateLimit({ window: '15m', max: 10, name: 'two-factor-management', key: () => String(getCurrentUser()?.id ?? ''), onCacheError: 'reject' })];\n\nasync function currentAccount() {\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string') throw new HttpError(401, 'Unauthorized');\n const id = principal.id;\n const kind = principal.role === 'admin' ? 'admin' : 'user';\n const model = kind === 'admin' ? Admin : User;\n const account = kind === 'admin' ? await Admin.findById(id) : await User.findById(id);\n if (!account || !account.isActive) throw new HttpError(403, 'Account unavailable');\n return { account, kind, model };\n}\n\nexport const POST = async (req, res) => {\n const { password, code } = req.body ?? {};\n if (typeof password !== 'string' || !password || (code !== undefined && (typeof code !== 'string' || !/^\\d{6}$/.test(code)))) return res.status(400).json({ error: 'password and a six-digit code are required' });\n const { account, kind, model } = await currentAccount();\n if (!(await verifyPassword(password, account.password))) return res.status(401).json({ error: 'Invalid credentials' });\n if (!account.twoFactorEnabled) return res.status(409).json({ error: 'Two-factor authentication is not enabled' });\n if (account.twoFactorMethod === 'email' && code === undefined) {\n await sendEmailCode(model, account, kind, 'disable');\n return res.status(202).json({ codeSent: true, expiresIn: 300 });\n }\n if (!(await acceptTwoFactor(model, account, kind, code, 'disable'))) return res.status(401).json({ error: 'Invalid or already used authenticator code' });\n const disabled = await updateSecurity(model, { id: account.id, twoFactorEnabled: true, twoFactorSecret: account.twoFactorSecret ?? '' }, {\n twoFactorEnabled: false, twoFactorMethod: '', twoFactorSecret: '', twoFactorLastStep: -1, twoFactorPendingSecret: '', twoFactorPendingMethod: '', twoFactorEmailHash: '', twoFactorEmailExpiry: new Date(0),\n twoFactorPendingExpiry: new Date(0), refreshToken: '', refreshTokenExpiry: new Date(0),\n });\n if (!disabled) return res.status(409).json({ error: 'Account changed; try again' });\n await revokeAllSessions(account.id);\n res.clearCookie('efc_refresh_token');\n res.json({ message: '2FA disabled; log in again' });\n};\n"},{"path":"src/api/auth/2fa/setup.js","content":"import { requireAuth, getCurrentUser, verifyPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { HttpError, rateLimit } from 'express-file-cluster';\nimport { User } from '../../../model/User.js';\nimport { Admin } from '../../../model/Admin.js';\nimport { newSecret, sealSecret, openSecret, codeStep, updateSecurity, acceptTwoFactor, allowedMethods, sendEmailCode, consumeEmailCode } from '../../../lib/two-factor.js';\n\nexport const middlewares = [requireAuth, rateLimit({ window: '15m', max: 10, name: 'two-factor-management', key: () => String(getCurrentUser()?.id ?? ''), onCacheError: 'reject' })];\n\nasync function currentAccount() {\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string') throw new HttpError(401, 'Unauthorized');\n const id = principal.id;\n const kind = principal.role === 'admin' ? 'admin' : 'user';\n const model = kind === 'admin' ? Admin : User;\n const account = kind === 'admin' ? await Admin.findById(id) : await User.findById(id);\n if (!account || !account.isActive) throw new HttpError(403, 'Account unavailable');\n return { account, kind, model };\n}\n\nexport const GET = async (_req, res) => {\n const { account } = await currentAccount();\n res.set('Cache-Control', 'no-store');\n res.json({ enabled: !!account.twoFactorEnabled, method: account.twoFactorMethod || null, methods: allowedMethods() });\n};\n\nexport const POST = async (req, res) => {\n res.set('Cache-Control', 'no-store');\n const { password, code, method = 'totp' } = req.body ?? {};\n if (typeof password !== 'string' || !password || (code !== undefined && (typeof code !== 'string' || !/^\\d{6}$/.test(code)))) return res.status(400).json({ error: 'password and a six-digit code (when confirming) are required' });\n const { account, kind, model } = await currentAccount();\n if (!(await verifyPassword(password, account.password))) return res.status(401).json({ error: 'Invalid credentials' });\n if (account.twoFactorEnabled) return res.status(409).json({ error: 'Two-factor authentication is already enabled' });\n const identity = kind + ':' + account.id;\n if (typeof method !== 'string' || !allowedMethods().includes(method)) return res.status(400).json({ error: 'Choose an allowed two-factor method' });\n if (code === undefined && method === 'email') {\n const updated = await updateSecurity(model, { id: account.id, twoFactorEnabled: false }, { twoFactorPendingMethod: 'email', twoFactorPendingSecret: '', twoFactorPendingExpiry: new Date(Date.now() + 300000) });\n if (!updated) return res.status(409).json({ error: 'Account changed; try again' });\n await sendEmailCode(model, account, kind, 'enroll');\n return res.status(202).json({ method: 'email', codeSent: true, expiresIn: 300 });\n }\n if (code === undefined) {\n const secret = newSecret();\n const encrypted = sealSecret(secret, identity);\n const updated = await updateSecurity(model, { id: account.id, twoFactorEnabled: false }, { twoFactorPendingMethod: 'totp', twoFactorPendingSecret: encrypted, twoFactorPendingExpiry: new Date(Date.now() + 600000) });\n if (!updated) return res.status(409).json({ error: 'Account changed; try again' });\n const issuer = 'EFC';\n const otpauthUrl = 'otpauth://totp/' + encodeURIComponent(issuer + ':' + account.email) + '?secret=' + secret + '&issuer=' + issuer + '&algorithm=SHA1&digits=6&period=30';\n return res.json({ method: 'totp', secret, otpauthUrl, expiresIn: 600 });\n }\n if (account.twoFactorPendingMethod !== method || !account.twoFactorPendingExpiry || new Date(account.twoFactorPendingExpiry).getTime() <= Date.now()) return res.status(400).json({ error: 'Enrollment expired; start again' });\n let step = -1;\n if (method === 'email') {\n if (!(await consumeEmailCode(model, account, kind, 'enroll', code))) return res.status(401).json({ error: 'Invalid or expired email code' });\n } else {\n if (!account.twoFactorPendingSecret) return res.status(400).json({ error: 'Start enrollment first' });\n const matched = codeStep(openSecret(account.twoFactorPendingSecret, identity), code);\n if (matched === undefined) return res.status(401).json({ error: 'Invalid authenticator code' });\n step = matched;\n }\n const enabled = await updateSecurity(model, { id: account.id, twoFactorEnabled: false, twoFactorPendingMethod: method, twoFactorPendingSecret: account.twoFactorPendingSecret ?? '' }, {\n twoFactorEnabled: true, twoFactorMethod: method, twoFactorSecret: method === 'totp' ? (account.twoFactorPendingSecret ?? '') : '', twoFactorLastStep: step,\n twoFactorPendingMethod: '', twoFactorPendingSecret: '', twoFactorPendingExpiry: new Date(0), refreshToken: '', refreshTokenExpiry: new Date(0),\n });\n if (!enabled) return res.status(409).json({ error: 'Enrollment changed; start again' });\n await revokeAllSessions(account.id);\n res.clearCookie('efc_refresh_token');\n res.json({ message: '2FA enabled; log in again with your verification code' });\n};\n"},{"path":"src/api/auth/2fa/verify.js","content":"export { middlewares, POST } from '../login.js';\n"},{"path":"src/api/auth/change-password.js","content":"import { requireAuth, getCurrentUser, hashPassword, verifyPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { rateLimit } from 'express-file-cluster';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Change password for the authenticated user.',\n request: { body: { oldPassword: 'current', newPassword: 'newpassword' } },\n response: { status: 200, body: { message: 'Password changed successfully' } },\n },\n};\n\n\nexport const middlewares = [\n requireAuth('user', 'admin'),\n rateLimit({ window: '15m', max: 10, name: 'change-password', key: () => String(getCurrentUser()?.id ?? '') }),\n];\n\nexport const POST = async (req, res) => {\n const { oldPassword, newPassword } = req.body ?? {};\n if (typeof oldPassword !== 'string' || typeof newPassword !== 'string' || !oldPassword || !newPassword) {\n return res.status(400).json({ error: 'oldPassword and newPassword are required' });\n }\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string' || !principal.id) return res.status(401).json({ error: 'Unauthorized' });\n const id = principal.id;\n const isAdmin = principal.role === 'admin';\n const account = isAdmin ? await Admin.findById(id) : await User.findById(id);\n if (!account || !(await verifyPassword(oldPassword, account.password))) {\n return res.status(401).json({ error: 'Invalid credentials' });\n }\n if (!account.isActive) return res.status(403).json({ error: 'Account suspended' });\n const hashed = await hashPassword(newPassword);\n const updated = isAdmin ? await Admin.update(id, { password: hashed, refreshToken: '', refreshTokenExpiry: new Date(0), resetToken: '', resetTokenExpiry: new Date(0) }) : await User.update(id, { password: hashed, refreshToken: '', refreshTokenExpiry: new Date(0), resetToken: '', resetTokenExpiry: new Date(0) });\n if (!updated) return res.status(404).json({ error: 'Account not found' });\n await revokeAllSessions(id);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Password changed successfully' });\n};\n"},{"path":"src/api/auth/refresh.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Refresh the JWT using the refresh-token cookie and issue a new access token.',\n response: { status: 200, body: { message: 'Token refreshed' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nexport const POST = async (req, res) => {\n const authenticatedAt = Date.now();\n const token = req.cookies?.efc_refresh_token || req.body?.refreshToken;\n if (!token) return res.status(401).json({ error: 'Refresh token required' });\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') return res.status(400).json({ error: 'Invalid refresh token' });\n\n const user = await User.findOne({ refreshToken: token });\n const admin = user ? null : await Admin.findOne({ refreshToken: token });\n const account = user || admin;\n\n if (!account || !account.refreshTokenExpiry || new Date(account.refreshTokenExpiry) < new Date()) {\n return res.status(401).json({ error: 'Invalid or expired refresh token' });\n }\n if (account.isActive === false) return res.status(403).json({ error: 'Account suspended' });\n\n const newRefreshToken = crypto.randomBytes(40).toString('hex');\n const refreshTokenExpiry = new Date(Date.now() + REFRESH_TOKEN_TTL_MS);\n const model = user ? User : Admin;\n const rotated = await updateSecurity(model, { id: account.id, refreshToken: token, twoFactorEnabled: !!account.twoFactorEnabled }, { refreshToken: newRefreshToken, refreshTokenExpiry });\n if (!rotated) return res.status(401).json({ error: 'Refresh token expired or already used' });\n\n res.cookie('efc_refresh_token', newRefreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n\n const accessToken = await issueToken(res, { id: account.id, role: account.role, email: account.email, efc_auth_at: authenticatedAt });\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({\n message: 'Token refreshed',\n ...(accessToken ? { token: accessToken, refreshToken: newRefreshToken } : {}),\n });\n};\n"},{"path":"src/api/auth/sessions/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n DELETE: {\n description: 'Device session management extension point (not implemented).',\n response: { status: 501, body: {\"error\":\"Device session management is not implemented. Connect an implementation before enabling this feature.\",\"statusCode\":501} },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\n// Extension point: replace this handler only after wiring and testing the feature.\nexport const DELETE = (_req, res) => {\n res.status(501).json({ error: \"Device session management is not implemented. Connect an implementation before enabling this feature.\", statusCode: 501 });\n};\n"},{"path":"src/api/auth/sessions/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Device session management extension point (not implemented).',\n response: { status: 501, body: {\"error\":\"Device session management is not implemented. Connect an implementation before enabling this feature.\",\"statusCode\":501} },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\n// Extension point: replace this handler only after wiring and testing the feature.\nexport const GET = (_req, res) => {\n res.status(501).json({ error: \"Device session management is not implemented. Connect an implementation before enabling this feature.\", statusCode: 501 });\n};\n"},{"path":"src/model/Session.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Session = defineModel('Session', {\n userId: { type: 'string', required: true },\n token: { type: 'string', required: true, unique: true },\n ip: { type: 'string', required: true },\n userAgent: { type: 'string', required: true },\n expiresAt: { type: 'date', required: true },\n isActive: { type: 'boolean', default: true },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[{"key":"TWO_FACTOR_METHOD","value":"totp","example":"totp"}]}
@@ -1 +1 @@
1
- {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n // The role lives in the user's JWTs: end them, or a demoted/suspended user keeps access\n // until they expire. (/auth/refresh also refuses inactive accounts.)\n if (role !== undefined || isActive === false) await revokeAllSessions(id);\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n await revokeAllSessions(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false (then revokeAllSessions(id) so open sessions end), log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n // 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.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n // The role lives in the user's JWTs: end them, or a demoted/suspended user keeps access\n // until they expire. (/auth/refresh also refuses inactive accounts.)\n if (role !== undefined || isActive === false) await revokeAllSessions(id);\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n await revokeAllSessions(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false (then revokeAllSessions(id) so open sessions end), log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n // 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.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport { rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\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(res, model, id) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n return refreshToken;\n}\n\nexport const POST = async (req, res) => {\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.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n 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.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n 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.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n // 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.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: _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.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport { HttpError, rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { acceptTwoFactor, updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\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 name: 'password-login',\n onCacheError: 'reject',\n key: (req) => String(req.body?.email ?? '').toLowerCase(),\n }),\n];\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, account) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n const updated = await updateSecurity(model, { id: account.id, password: account.password, twoFactorEnabled: !!account.twoFactorEnabled, ...(account.twoFactorEnabled ? { twoFactorSecret: account.twoFactorSecret ?? '' } : {}) }, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n if (!updated) throw new HttpError(409, 'Account security changed; log in again');\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, res) => {\n const authenticatedAt = Date.now();\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.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n if (!(await acceptTwoFactor(Admin, admin, 'admin', req.body?.code))) return res.status(401).json({ error: 'Verification code required or invalid', twoFactorRequired: true, method: admin.twoFactorMethod || 'totp' });\n const refreshToken = await issueRefreshToken(res, Admin, admin);\n const token = await issueToken(res, { id: admin.id, role: admin.role, email: admin.email, efc_auth_at: authenticatedAt });\n return res.json({ message: 'Logged in as admin', ...(token ? { token, refreshToken } : {}) });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n if (!(await acceptTwoFactor(User, user, 'user', req.body?.code))) return res.status(401).json({ error: 'Verification code required or invalid', twoFactorRequired: true, method: user.twoFactorMethod || 'totp' });\n const refreshToken = await issueRefreshToken(res, User, user);\n const token = await issueToken(res, { id: user.id, role: user.role, email: user.email, efc_auth_at: authenticatedAt });\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.js","content":"import { requireAuth, getCurrentUser, revokeSession } from 'express-file-cluster/auth';\nimport { updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const middlewares = [requireAuth];\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string') return res.status(401).json({ error: 'Unauthorized' });\n const id = principal.id;\n const user = principal.role === 'admin' ? null : await User.findById(id);\n if (user?.refreshToken) await updateSecurity(User, { id, refreshToken: user.refreshToken }, { refreshToken: '', refreshTokenExpiry: new Date(0) });\n const admin = principal.role === 'admin' ? await Admin.findById(id) : null;\n if (admin?.refreshToken) await updateSecurity(Admin, { id, refreshToken: admin.refreshToken }, { refreshToken: '', refreshTokenExpiry: new Date(0) });\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n // 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.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/lib/two-factor.js","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { enqueue } from 'express-file-cluster/tasks';\n\n\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\nexport function newSecret() {\n const bytes = crypto.randomBytes(20);\n let bits = 0, value = 0, result = '';\n for (const byte of bytes) {\n value = (value << 8) | byte; bits += 8;\n while (bits >= 5) { bits -= 5; result += ALPHABET[(value >>> bits) & 31]; }\n }\n return result;\n}\nfunction secretBytes(secret) {\n if (!/^[A-Z2-7]+$/.test(secret)) throw new Error('Invalid TOTP secret');\n let bits = 0, value = 0;\n const bytes = [];\n for (const char of secret) {\n value = (value << 5) | ALPHABET.indexOf(char); bits += 5;\n if (bits >= 8) { bits -= 8; bytes.push((value >>> bits) & 255); }\n }\n return Buffer.from(bytes);\n}\n// RFC 6238: SHA-1, six digits, 30-second steps, one step of clock drift.\nexport function totp(secret, step) {\n const counter = Buffer.alloc(8);\n counter.writeBigUInt64BE(BigInt(step));\n const digest = crypto.createHmac('sha1', secretBytes(secret)).update(counter).digest();\n const offset = digest[digest.length - 1] & 15;\n return String((digest.readUInt32BE(offset) & 0x7fffffff) % 1000000).padStart(6, '0');\n}\nexport function codeStep(secret, code, last = -1, now = Date.now()) {\n if (typeof code !== 'string' || !/^\\d{6}$/.test(code)) return undefined;\n const step = Math.floor(now / 30000);\n for (const candidate of [step, step - 1, step + 1]) {\n if (candidate > last && candidate >= 0 && crypto.timingSafeEqual(Buffer.from(code), Buffer.from(totp(secret, candidate)))) return candidate;\n }\n return undefined;\n}\nfunction encryptionKey() {\n const key = process.env.TWO_FACTOR_KEY;\n if (!key || !/^[a-fA-F0-9]{64}$/.test(key)) throw new HttpError(503, 'TWO_FACTOR_KEY must be 32 random bytes encoded as 64 hex characters');\n return Buffer.from(key, 'hex');\n}\nexport function sealSecret(secret, identity) {\n const iv = crypto.randomBytes(12);\n const cipher = crypto.createCipheriv('aes-256-gcm', encryptionKey(), iv);\n cipher.setAAD(Buffer.from(identity));\n const encrypted = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);\n return Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString('base64url');\n}\nexport function openSecret(encrypted, identity) {\n const key = encryptionKey();\n try {\n const data = Buffer.from(encrypted, 'base64url');\n const decipher = crypto.createDecipheriv('aes-256-gcm', key, data.subarray(0, 12));\n decipher.setAAD(Buffer.from(identity));\n decipher.setAuthTag(data.subarray(12, 28));\n return Buffer.concat([decipher.update(data.subarray(28)), decipher.final()]).toString('utf8');\n } catch { throw new HttpError(503, 'Two-factor secret could not be decrypted'); }\n}\nexport async function updateSecurity(model, where, data) {\n // Older MongoDB records may predate the defaulted enabled flag. Missing means off.\n if (where.twoFactorEnabled === false) where = { ...where, twoFactorEnabled: { $ne: true } };\n const result = await model.updateMany(where, data);\n return result === 1;\n}\nexport function allowedMethods() {\n const value = process.env.TWO_FACTOR_METHOD ?? 'totp';\n if (!['totp', 'email', 'both'].includes(value)) throw new HttpError(503, 'Invalid TWO_FACTOR_METHOD');\n return value === 'both' ? ['totp', 'email'] : [value];\n}\nfunction emailDigest(identity, purpose, code) {\n return crypto.createHmac('sha256', encryptionKey()).update(identity + ':' + purpose + ':' + code).digest('hex');\n}\nexport async function sendEmailCode(model, account, kind, purpose) {\n if (!process.env.SMTP_HOST) throw new HttpError(503, 'Configure the email-client SMTP settings before using email OTP');\n const code = String(crypto.randomInt(0, 1000000)).padStart(6, '0');\n const twoFactorEmailHash = emailDigest(kind + ':' + account.id + ':' + account.email, purpose, code);\n const updated = await updateSecurity(model, { id: account.id, twoFactorEnabled: !!account.twoFactorEnabled }, {\n twoFactorEmailHash, twoFactorEmailExpiry: new Date(Date.now() + 300000), twoFactorEmailPurpose: purpose,\n });\n if (!updated) throw new HttpError(409, 'Account security changed; try again');\n try {\n await enqueue('SendEmail', { to: account.email, subject: 'Your EFC verification code', body: 'Your verification code is <b>' + code + '</b>. It expires in 5 minutes.' });\n } catch (error) {\n await updateSecurity(model, { id: account.id, twoFactorEmailHash }, { twoFactorEmailHash: '' });\n throw error;\n }\n}\nexport async function consumeEmailCode(model, account, kind, purpose, code) {\n if (typeof code !== 'string' || !/^\\d{6}$/.test(code) || !account.twoFactorEmailHash || account.twoFactorEmailPurpose !== purpose || !account.twoFactorEmailExpiry || new Date(account.twoFactorEmailExpiry).getTime() <= Date.now()) return false;\n const digest = emailDigest(kind + ':' + account.id + ':' + account.email, purpose, code);\n const stored = Buffer.from(account.twoFactorEmailHash, 'hex');\n const supplied = Buffer.from(digest, 'hex');\n if (stored.length !== supplied.length || !crypto.timingSafeEqual(stored, supplied)) return false;\n return updateSecurity(model, { id: account.id, twoFactorEmailHash: account.twoFactorEmailHash, twoFactorEnabled: !!account.twoFactorEnabled }, { twoFactorEmailHash: '', twoFactorEmailExpiry: new Date(0) });\n}\nexport async function acceptTwoFactor(model, account, kind, code, purpose = 'login') {\n if (!account.twoFactorEnabled) return true;\n const method = account.twoFactorMethod ?? 'totp';\n if (!allowedMethods().includes(method)) return false;\n if (method === 'email') {\n if (code === undefined) { await sendEmailCode(model, account, kind, purpose); return false; }\n return consumeEmailCode(model, account, kind, purpose, code);\n }\n if (!account.twoFactorSecret) return false;\n const step = codeStep(openSecret(account.twoFactorSecret, kind + ':' + account.id), code, account.twoFactorLastStep ?? -1);\n if (step === undefined) return false;\n // Compare-and-set in the database: only one worker can accept a given code.\n return updateSecurity(model, { id: account.id, twoFactorEnabled: true, twoFactorSecret: account.twoFactorSecret, twoFactorLastStep: { $lt: step } }, { twoFactorLastStep: step });\n}\n"},{"path":"src/model/Admin.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const Admin = defineModel('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n twoFactorEnabled: { type: 'boolean', default: false },\n twoFactorSecret: { type: 'string', default: '' },\n twoFactorLastStep: { type: 'number', default: -1 },\n twoFactorPendingSecret: { type: 'string', default: '' },\n twoFactorPendingExpiry: { type: 'date' },\n twoFactorMethod: { type: 'string', default: '' },\n twoFactorPendingMethod: { type: 'string', default: '' },\n twoFactorEmailHash: { type: 'string', default: '' },\n twoFactorEmailExpiry: { type: 'date' },\n twoFactorEmailPurpose: { type: 'string', default: '' },\n});\n"},{"path":"src/model/User.js","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n twoFactorEnabled: { type: 'boolean', default: false },\n twoFactorSecret: { type: 'string', default: '' },\n twoFactorLastStep: { type: 'number', default: -1 },\n twoFactorPendingSecret: { type: 'string', default: '' },\n twoFactorPendingExpiry: { type: 'date' },\n twoFactorMethod: { type: 'string', default: '' },\n twoFactorPendingMethod: { type: 'string', default: '' },\n twoFactorEmailHash: { type: 'string', default: '' },\n twoFactorEmailExpiry: { type: 'date' },\n twoFactorEmailPurpose: { type: 'string', default: '' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n const token = await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { appChallengeFrom, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req, res) => {\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.js","content":"import { exchangeCode } from '../../../lib/oauth.js';\nexport const meta = {\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, res) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n // 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) {\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,\n appChallenge,\n) {\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, verifier) {\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(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.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
1
+ {"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret() {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req, res) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n const token = await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/apple/index.js","content":"import { appChallengeFrom, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req, res) => {\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.js","content":"import { exchangeCode } from '../../../lib/oauth.js';\nexport const meta = {\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, res) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n if (user.twoFactorEnabled) throw new HttpError(403, 'Use password login with an authenticator code for this account');\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) {\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,\n appChallenge,\n) {\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, verifier) {\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(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.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
@@ -1 +1 @@
1
- {"name":"auth@google","files":[{"path":"src/api/auth/google/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req, res) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n const token = await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true,\n name: payload.name,\n });\n res.redirect(await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/google/index.js","content":"import { appChallengeFrom, pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req, res) => {\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.js","content":"import { exchangeCode } from '../../../lib/oauth.js';\nexport const meta = {\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, res) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n // 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) {\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,\n appChallenge,\n) {\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, verifier) {\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(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.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
1
+ {"name":"auth@google","files":[{"path":"src/api/auth/google/callback.js","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req, res) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json());\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n const token = await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email,\n emailVerified: payload.email_verified === true,\n name: payload.name,\n });\n res.redirect(await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/google/index.js","content":"import { appChallengeFrom, pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nexport const meta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req, res) => {\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.js","content":"import { exchangeCode } from '../../../lib/oauth.js';\nexport const meta = {\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, res) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.js","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken() {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier) {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res,\n provider,\n data,\n crossSite = false,\n) {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req,\n res,\n provider,\n state,\n) {\n const name = `efc_oauth_${provider}`;\n const raw = req.cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw);\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res, profile) {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n if (user.twoFactorEnabled) throw new HttpError(403, 'Use password login with an authenticator code for this account');\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) {\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,\n appChallenge,\n) {\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, verifier) {\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(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.js","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
@@ -1 +1 @@
1
- {"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import 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';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\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, res) => {\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.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body;\n // 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.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.js","content":"import 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';\nexport const meta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\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, res) => {\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.findOne({ email });\n const admin = user ? null : await Admin.findOne({ email });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update(user.id, { resetToken, resetTokenExpiry });\n else if (admin) await Admin.update(admin.id, { resetToken, resetTokenExpiry });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.js","content":"import { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { token, password } = req.body ?? {};\n // 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.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n const consumed = await updateSecurity(user ? User : Admin, { id: account.id, resetToken: token, resetTokenExpiry: { $gt: new Date() } }, { password: hashed, resetToken: '', resetTokenExpiry: new Date(0), refreshToken: '', refreshTokenExpiry: new Date(0), twoFactorPendingSecret: '', twoFactorPendingMethod: '', twoFactorPendingExpiry: new Date(0), twoFactorEmailHash: '', twoFactorEmailExpiry: new Date(0) });\n if (!consumed) return res.status(400).json({ error: 'Invalid, expired or already used reset token' });\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.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nexport const meta = {\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, res) => {\n const { id } = req.user;\n const user = await User.findById(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, res) => {\n const { id } = req.user;\n const { name, email } = req.body;\n const updated = await User.update(id, { 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":[]}
1
+ {"name":"user-profile","files":[{"path":"src/api/user/profile.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nexport const meta = {\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, res) => {\n const { id } = req.user;\n const user = await User.findById(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, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.user;\n const { name, email } = req.body ?? {};\n if ((name !== undefined && typeof name !== 'string') || (email !== undefined && typeof email !== 'string')) return res.status(400).json({ error: 'name and email must be strings' });\n const existing = await User.findById(id);\n if (!existing) return res.status(404).json({ error: 'User not found' });\n if (email !== undefined && email !== existing.email && existing.twoFactorEnabled && existing.twoFactorMethod === 'email') return res.status(409).json({ error: 'Disable email 2FA before changing the email address' });\n const updated = await User.update(id, { 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, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = updated;\n res.json({ message: 'Profile updated', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Disable 2FA for the authenticated user.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA disabled' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify code and disable 2FA\n res.json({ message: '2FA disabled' });\n};\n"},{"path":"src/api/auth/2fa/setup.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Generate a TOTP secret and QR code to set up 2FA.',\n response: { status: 200, body: { qrCode: 'otpauth://totp/...', secret: 'BASE32SECRET' } },\n },\n POST: {\n description: 'Confirm a TOTP code to enable 2FA for the authenticated user.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA enabled' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: generate TOTP secret and return QR code URL\n res.json({ qrCode: 'otpauth://totp/...', secret: 'BASE32SECRET' });\n};\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify TOTP code and enable 2FA\n res.json({ message: '2FA enabled' });\n};\n"},{"path":"src/api/auth/2fa/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Verify a TOTP code during login.',\n request: { body: { code: '123456' } },\n response: { status: 200, body: { message: '2FA verified' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { code } = req.body;\n if (!code) return res.status(400).json({ error: 'code is required' });\n // TODO: verify TOTP code\n res.json({ message: '2FA verified' });\n};\n"},{"path":"src/api/auth/change-password.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Change password for the authenticated user.',\n request: { body: { oldPassword: 'current', newPassword: 'newpassword' } },\n response: { status: 200, body: { message: 'Password changed successfully' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req, res) => {\n const { oldPassword, newPassword } = req.body;\n if (!oldPassword || !newPassword) return res.status(400).json({ error: 'oldPassword and newPassword are required' });\n // TODO: verify old password, hash and update new password, then sign out other devices:\n // await revokeAllSessions(req.user.id) (import from 'express-file-cluster/auth')\n res.json({ message: 'Password changed successfully' });\n};\n"},{"path":"src/api/auth/refresh.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Refresh the JWT using the refresh-token cookie and issue a new access token.',\n response: { status: 200, body: { message: 'Token refreshed' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nexport const POST = async (req, res) => {\n const token = req.cookies?.efc_refresh_token || req.body?.refreshToken;\n if (!token) return res.status(401).json({ error: 'Refresh token required' });\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') return res.status(400).json({ error: 'Invalid refresh token' });\n\n const user = await User.findFirst({ where: { refreshToken: token } });\n const admin = user ? null : await Admin.findFirst({ where: { refreshToken: token } });\n const account = user || admin;\n\n if (!account || !account.refreshTokenExpiry || new Date(account.refreshTokenExpiry) < new Date()) {\n return res.status(401).json({ error: 'Invalid or expired refresh token' });\n }\n if (account.isActive === false) return res.status(403).json({ error: 'Account suspended' });\n\n const newRefreshToken = crypto.randomBytes(40).toString('hex');\n const refreshTokenExpiry = new Date(Date.now() + REFRESH_TOKEN_TTL_MS);\n if (user) await User.update({ where: { id: user.id }, data: { refreshToken: newRefreshToken, refreshTokenExpiry } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { refreshToken: newRefreshToken, refreshTokenExpiry } });\n\n res.cookie('efc_refresh_token', newRefreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n\n const accessToken = await issueToken(res, { id: account.id, role: account.role, email: account.email });\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({\n message: 'Token refreshed',\n ...(accessToken ? { token: accessToken, refreshToken: newRefreshToken } : {}),\n });\n};\n"},{"path":"src/api/auth/sessions/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n DELETE: {\n description: 'Revoke a single active session by ID.',\n request: { params: { id: 'sess_01HXZ' } },\n response: { status: 200, body: { message: 'Session sess_01HXZ revoked' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n // TODO: revoke session by id\n res.json({ message: `Session ${id} revoked` });\n};\n"},{"path":"src/api/auth/sessions/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'List all active sessions for the authenticated user.',\n response: { status: 200, body: { sessions: [] } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n // TODO: fetch sessions for req.user.id\n res.json({ sessions: [] });\n};\n"},{"path":"src/model/Session.js","content":"import { defineTable } from 'express-file-cluster';\n\nexport const Session = defineTable('Session', {\n user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\n token: { type: 'string', required: true, unique: true },\n ip: { type: 'string', required: true },\n userAgent: { type: 'string', required: true },\n expiresAt: { type: 'date', required: true },\n isActive: { type: 'boolean', default: true },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.js","content":"import { requireAuth, getCurrentUser, verifyPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { HttpError, rateLimit } from 'express-file-cluster';\nimport { User } from '../../../model/User.js';\nimport { Admin } from '../../../model/Admin.js';\nimport { newSecret, sealSecret, openSecret, codeStep, updateSecurity, acceptTwoFactor, allowedMethods, sendEmailCode, consumeEmailCode } from '../../../lib/two-factor.js';\n\nexport const middlewares = [requireAuth, rateLimit({ window: '15m', max: 10, name: 'two-factor-management', key: () => String(getCurrentUser()?.id ?? ''), onCacheError: 'reject' })];\n\nasync function currentAccount() {\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string') throw new HttpError(401, 'Unauthorized');\n const id = principal.id;\n const kind = principal.role === 'admin' ? 'admin' : 'user';\n const model = kind === 'admin' ? Admin : User;\n const account = kind === 'admin' ? await Admin.findUnique({ where: { id } }) : await User.findUnique({ where: { id } });\n if (!account || !account.isActive) throw new HttpError(403, 'Account unavailable');\n return { account, kind, model };\n}\n\nexport const POST = async (req, res) => {\n const { password, code } = req.body ?? {};\n if (typeof password !== 'string' || !password || (code !== undefined && (typeof code !== 'string' || !/^\\d{6}$/.test(code)))) return res.status(400).json({ error: 'password and a six-digit code are required' });\n const { account, kind, model } = await currentAccount();\n if (!(await verifyPassword(password, account.password))) return res.status(401).json({ error: 'Invalid credentials' });\n if (!account.twoFactorEnabled) return res.status(409).json({ error: 'Two-factor authentication is not enabled' });\n if (account.twoFactorMethod === 'email' && code === undefined) {\n await sendEmailCode(model, account, kind, 'disable');\n return res.status(202).json({ codeSent: true, expiresIn: 300 });\n }\n if (!(await acceptTwoFactor(model, account, kind, code, 'disable'))) return res.status(401).json({ error: 'Invalid or already used authenticator code' });\n const disabled = await updateSecurity(model, { id: account.id, twoFactorEnabled: true, twoFactorSecret: account.twoFactorSecret ?? '' }, {\n twoFactorEnabled: false, twoFactorMethod: '', twoFactorSecret: '', twoFactorLastStep: -1, twoFactorPendingSecret: '', twoFactorPendingMethod: '', twoFactorEmailHash: '', twoFactorEmailExpiry: new Date(0),\n twoFactorPendingExpiry: new Date(0), refreshToken: '', refreshTokenExpiry: new Date(0),\n });\n if (!disabled) return res.status(409).json({ error: 'Account changed; try again' });\n await revokeAllSessions(account.id);\n res.clearCookie('efc_refresh_token');\n res.json({ message: '2FA disabled; log in again' });\n};\n"},{"path":"src/api/auth/2fa/setup.js","content":"import { requireAuth, getCurrentUser, verifyPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { HttpError, rateLimit } from 'express-file-cluster';\nimport { User } from '../../../model/User.js';\nimport { Admin } from '../../../model/Admin.js';\nimport { newSecret, sealSecret, openSecret, codeStep, updateSecurity, acceptTwoFactor, allowedMethods, sendEmailCode, consumeEmailCode } from '../../../lib/two-factor.js';\n\nexport const middlewares = [requireAuth, rateLimit({ window: '15m', max: 10, name: 'two-factor-management', key: () => String(getCurrentUser()?.id ?? ''), onCacheError: 'reject' })];\n\nasync function currentAccount() {\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string') throw new HttpError(401, 'Unauthorized');\n const id = principal.id;\n const kind = principal.role === 'admin' ? 'admin' : 'user';\n const model = kind === 'admin' ? Admin : User;\n const account = kind === 'admin' ? await Admin.findUnique({ where: { id } }) : await User.findUnique({ where: { id } });\n if (!account || !account.isActive) throw new HttpError(403, 'Account unavailable');\n return { account, kind, model };\n}\n\nexport const GET = async (_req, res) => {\n const { account } = await currentAccount();\n res.set('Cache-Control', 'no-store');\n res.json({ enabled: !!account.twoFactorEnabled, method: account.twoFactorMethod || null, methods: allowedMethods() });\n};\n\nexport const POST = async (req, res) => {\n res.set('Cache-Control', 'no-store');\n const { password, code, method = 'totp' } = req.body ?? {};\n if (typeof password !== 'string' || !password || (code !== undefined && (typeof code !== 'string' || !/^\\d{6}$/.test(code)))) return res.status(400).json({ error: 'password and a six-digit code (when confirming) are required' });\n const { account, kind, model } = await currentAccount();\n if (!(await verifyPassword(password, account.password))) return res.status(401).json({ error: 'Invalid credentials' });\n if (account.twoFactorEnabled) return res.status(409).json({ error: 'Two-factor authentication is already enabled' });\n const identity = kind + ':' + account.id;\n if (typeof method !== 'string' || !allowedMethods().includes(method)) return res.status(400).json({ error: 'Choose an allowed two-factor method' });\n if (code === undefined && method === 'email') {\n const updated = await updateSecurity(model, { id: account.id, twoFactorEnabled: false }, { twoFactorPendingMethod: 'email', twoFactorPendingSecret: '', twoFactorPendingExpiry: new Date(Date.now() + 300000) });\n if (!updated) return res.status(409).json({ error: 'Account changed; try again' });\n await sendEmailCode(model, account, kind, 'enroll');\n return res.status(202).json({ method: 'email', codeSent: true, expiresIn: 300 });\n }\n if (code === undefined) {\n const secret = newSecret();\n const encrypted = sealSecret(secret, identity);\n const updated = await updateSecurity(model, { id: account.id, twoFactorEnabled: false }, { twoFactorPendingMethod: 'totp', twoFactorPendingSecret: encrypted, twoFactorPendingExpiry: new Date(Date.now() + 600000) });\n if (!updated) return res.status(409).json({ error: 'Account changed; try again' });\n const issuer = 'EFC';\n const otpauthUrl = 'otpauth://totp/' + encodeURIComponent(issuer + ':' + account.email) + '?secret=' + secret + '&issuer=' + issuer + '&algorithm=SHA1&digits=6&period=30';\n return res.json({ method: 'totp', secret, otpauthUrl, expiresIn: 600 });\n }\n if (account.twoFactorPendingMethod !== method || !account.twoFactorPendingExpiry || new Date(account.twoFactorPendingExpiry).getTime() <= Date.now()) return res.status(400).json({ error: 'Enrollment expired; start again' });\n let step = -1;\n if (method === 'email') {\n if (!(await consumeEmailCode(model, account, kind, 'enroll', code))) return res.status(401).json({ error: 'Invalid or expired email code' });\n } else {\n if (!account.twoFactorPendingSecret) return res.status(400).json({ error: 'Start enrollment first' });\n const matched = codeStep(openSecret(account.twoFactorPendingSecret, identity), code);\n if (matched === undefined) return res.status(401).json({ error: 'Invalid authenticator code' });\n step = matched;\n }\n const enabled = await updateSecurity(model, { id: account.id, twoFactorEnabled: false, twoFactorPendingMethod: method, twoFactorPendingSecret: account.twoFactorPendingSecret ?? '' }, {\n twoFactorEnabled: true, twoFactorMethod: method, twoFactorSecret: method === 'totp' ? (account.twoFactorPendingSecret ?? '') : '', twoFactorLastStep: step,\n twoFactorPendingMethod: '', twoFactorPendingSecret: '', twoFactorPendingExpiry: new Date(0), refreshToken: '', refreshTokenExpiry: new Date(0),\n });\n if (!enabled) return res.status(409).json({ error: 'Enrollment changed; start again' });\n await revokeAllSessions(account.id);\n res.clearCookie('efc_refresh_token');\n res.json({ message: '2FA enabled; log in again with your verification code' });\n};\n"},{"path":"src/api/auth/2fa/verify.js","content":"export { middlewares, POST } from '../login.js';\n"},{"path":"src/api/auth/change-password.js","content":"import { requireAuth, getCurrentUser, hashPassword, verifyPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { rateLimit } from 'express-file-cluster';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Change password for the authenticated user.',\n request: { body: { oldPassword: 'current', newPassword: 'newpassword' } },\n response: { status: 200, body: { message: 'Password changed successfully' } },\n },\n};\n\n\nexport const middlewares = [\n requireAuth('user', 'admin'),\n rateLimit({ window: '15m', max: 10, name: 'change-password', key: () => String(getCurrentUser()?.id ?? '') }),\n];\n\nexport const POST = async (req, res) => {\n const { oldPassword, newPassword } = req.body ?? {};\n if (typeof oldPassword !== 'string' || typeof newPassword !== 'string' || !oldPassword || !newPassword) {\n return res.status(400).json({ error: 'oldPassword and newPassword are required' });\n }\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string' || !principal.id) return res.status(401).json({ error: 'Unauthorized' });\n const id = principal.id;\n const isAdmin = principal.role === 'admin';\n const account = isAdmin ? await Admin.findUnique({ where: { id } }) : await User.findUnique({ where: { id } });\n if (!account || !(await verifyPassword(oldPassword, account.password))) {\n return res.status(401).json({ error: 'Invalid credentials' });\n }\n if (!account.isActive) return res.status(403).json({ error: 'Account suspended' });\n const hashed = await hashPassword(newPassword);\n const updated = isAdmin ? await Admin.update({ where: { id }, data: { password: hashed, refreshToken: '', refreshTokenExpiry: new Date(0), resetToken: '', resetTokenExpiry: new Date(0) } }) : await User.update({ where: { id }, data: { password: hashed, refreshToken: '', refreshTokenExpiry: new Date(0), resetToken: '', resetTokenExpiry: new Date(0) } });\n if (!updated) return res.status(404).json({ error: 'Account not found' });\n await revokeAllSessions(id);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Password changed successfully' });\n};\n"},{"path":"src/api/auth/refresh.js","content":"import { issueToken } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Refresh the JWT using the refresh-token cookie and issue a new access token.',\n response: { status: 200, body: { message: 'Token refreshed' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nexport const POST = async (req, res) => {\n const authenticatedAt = Date.now();\n const token = req.cookies?.efc_refresh_token || req.body?.refreshToken;\n if (!token) return res.status(401).json({ error: 'Refresh token required' });\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') return res.status(400).json({ error: 'Invalid refresh token' });\n\n const user = await User.findFirst({ where: { refreshToken: token } });\n const admin = user ? null : await Admin.findFirst({ where: { refreshToken: token } });\n const account = user || admin;\n\n if (!account || !account.refreshTokenExpiry || new Date(account.refreshTokenExpiry) < new Date()) {\n return res.status(401).json({ error: 'Invalid or expired refresh token' });\n }\n if (account.isActive === false) return res.status(403).json({ error: 'Account suspended' });\n\n const newRefreshToken = crypto.randomBytes(40).toString('hex');\n const refreshTokenExpiry = new Date(Date.now() + REFRESH_TOKEN_TTL_MS);\n const model = user ? User : Admin;\n const rotated = await updateSecurity(model, { id: account.id, refreshToken: token, twoFactorEnabled: !!account.twoFactorEnabled }, { refreshToken: newRefreshToken, refreshTokenExpiry });\n if (!rotated) return res.status(401).json({ error: 'Refresh token expired or already used' });\n\n res.cookie('efc_refresh_token', newRefreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n\n const accessToken = await issueToken(res, { id: account.id, role: account.role, email: account.email, efc_auth_at: authenticatedAt });\n // bearer: the client stores both tokens itself; http-only: they travel as cookies.\n res.json({\n message: 'Token refreshed',\n ...(accessToken ? { token: accessToken, refreshToken: newRefreshToken } : {}),\n });\n};\n"},{"path":"src/api/auth/sessions/[id].js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n DELETE: {\n description: 'Device session management extension point (not implemented).',\n response: { status: 501, body: {\"error\":\"Device session management is not implemented. Connect an implementation before enabling this feature.\",\"statusCode\":501} },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\n// Extension point: replace this handler only after wiring and testing the feature.\nexport const DELETE = (_req, res) => {\n res.status(501).json({ error: \"Device session management is not implemented. Connect an implementation before enabling this feature.\", statusCode: 501 });\n};\n"},{"path":"src/api/auth/sessions/index.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Device session management extension point (not implemented).',\n response: { status: 501, body: {\"error\":\"Device session management is not implemented. Connect an implementation before enabling this feature.\",\"statusCode\":501} },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\n// Extension point: replace this handler only after wiring and testing the feature.\nexport const GET = (_req, res) => {\n res.status(501).json({ error: \"Device session management is not implemented. Connect an implementation before enabling this feature.\", statusCode: 501 });\n};\n"},{"path":"src/model/Session.js","content":"import { defineTable } from 'express-file-cluster';\n\nexport const Session = defineTable('Session', {\n user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\n token: { type: 'string', required: true, unique: true },\n ip: { type: 'string', required: true },\n userAgent: { type: 'string', required: true },\n expiresAt: { type: 'date', required: true },\n isActive: { type: 'boolean', default: true },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[{"key":"TWO_FACTOR_METHOD","value":"totp","example":"totp"}]}
@@ -1 +1 @@
1
- {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.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, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update({ where: { id }, data: { name, email, role, isActive } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n // The role lives in the user's JWTs: end them, or a demoted/suspended user keeps access\n // until they expire. (/auth/refresh also refuses inactive accounts.)\n if (role !== undefined || isActive === false) await revokeAllSessions(id);\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete({ where: { id } });\n await revokeAllSessions(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false (then revokeAllSessions(id) so open sessions end), log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.findMany(), User.count()]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n // 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 user = await User.create({ data: { name, email, password: hashed, role: role ?? 'user' } });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
1
+ {"name":"admin-users","files":[{"path":"src/api/admin/users/[id].js","content":"import { requireAuth, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'Fetch a single user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n PUT: {\n description: 'Update a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { name: 'Jane Doe', email: 'jane@example.com', role: 'user', isActive: true } },\n response: { status: 200, body: { message: 'User updated', user: { id: 'usr_01HXZ', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n DELETE: {\n description: 'Delete a user by ID (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const { id } = req.params;\n const user = await User.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, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req, res) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update({ where: { id }, data: { name, email, role, isActive } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n // The role lives in the user's JWTs: end them, or a demoted/suspended user keeps access\n // until they expire. (/auth/refresh also refuses inactive accounts.)\n if (role !== undefined || isActive === false) await revokeAllSessions(id);\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req, res) => {\n const { id } = req.params;\n const user = await User.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete({ where: { id } });\n await revokeAllSessions(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Reactivate a suspended user account (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ activated' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isActive = true, log audit event\n res.json({ message: `User ${id} activated` });\n};\n"},{"path":"src/api/admin/users/[id]/suspend.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Suspend a user account (admin only).',\n request: { params: { id: 'usr_01HXZ' }, body: { reason: 'Terms of service violation' } },\n response: { status: 200, body: { message: 'User usr_01HXZ suspended', reason: 'Terms of service violation' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false (then revokeAllSessions(id) so open sessions end), log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Mark a user\\'s email as verified (admin only).',\n request: { params: { id: 'usr_01HXZ' } },\n response: { status: 200, body: { message: 'User usr_01HXZ verified' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req, res) => {\n const { id } = req.params;\n // TODO: set user.isVerified = true\n res.json({ message: `User ${id} verified` });\n};\n"},{"path":"src/api/admin/users/export.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Export all users as a CSV download (admin only).',\n response: { status: 200, body: 'id,name,email,role,createdAt\\n' },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req, res) => {\n // TODO: generate CSV of all users and stream response\n res.setHeader('Content-Type', 'text/csv');\n res.setHeader('Content-Disposition', 'attachment; filename=\"users.csv\"');\n res.send('id,name,email,role,createdAt\\n');\n};\n"},{"path":"src/api/admin/users/index.js","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport { User } from '../../../model/User.js';\nexport const meta = {\n GET: {\n description: 'List all users, paginated (admin only).',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { users: [], total: 0, page: 1, limit: 20 } },\n },\n POST: {\n description: 'Create a new user account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret', role: 'user' } },\n response: { status: 201, body: { message: 'User created', user: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'user' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req, res) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.findMany(), User.count()]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password, role } = req.body;\n // 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 user = await User.create({ data: { name, email, password: hashed, role: role ?? 'user' } });\n const { password: _, verifyToken: _vt, resetToken: _rt, resetTokenExpiry: _re, refreshToken: _ft, refreshTokenExpiry: _fe, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
@@ -1 +1 @@
1
- {"name":"auth","files":[{"path":"src/api/auth/login.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport { rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\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(res, model, id) {\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, res) => {\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.js","content":"import { revokeSession } from 'express-file-cluster/auth';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n // 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.js","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.js","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.js","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport { HttpError, rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { acceptTwoFactor, updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\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 name: 'password-login',\n onCacheError: 'reject',\n key: (req) => String(req.body?.email ?? '').toLowerCase(),\n }),\n];\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(res, model, account) {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n const updated = await updateSecurity(model, { id: account.id, password: account.password, twoFactorEnabled: !!account.twoFactorEnabled, ...(account.twoFactorEnabled ? { twoFactorSecret: account.twoFactorSecret ?? '' } : {}) }, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n if (!updated) throw new HttpError(409, 'Account security changed; log in again');\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, res) => {\n const authenticatedAt = Date.now();\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 if (!(await acceptTwoFactor(Admin, admin, 'admin', req.body?.code))) return res.status(401).json({ error: 'Verification code required or invalid', twoFactorRequired: true, method: admin.twoFactorMethod || 'totp' });\n const refreshToken = await issueRefreshToken(res, Admin, admin);\n const token = await issueToken(res, { id: admin.id, role: admin.role, email: admin.email, efc_auth_at: authenticatedAt });\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 if (!(await acceptTwoFactor(User, user, 'user', req.body?.code))) return res.status(401).json({ error: 'Verification code required or invalid', twoFactorRequired: true, method: user.twoFactorMethod || 'totp' });\n const refreshToken = await issueRefreshToken(res, User, user);\n const token = await issueToken(res, { id: user.id, role: user.role, email: user.email, efc_auth_at: authenticatedAt });\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.js","content":"import { requireAuth, getCurrentUser, revokeSession } from 'express-file-cluster/auth';\nimport { updateSecurity } from '../../lib/two-factor.js';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nexport const meta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const middlewares = [requireAuth];\n\nexport const POST = async (req, res) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n const principal = getCurrentUser();\n if (!principal || typeof principal.id !== 'string') return res.status(401).json({ error: 'Unauthorized' });\n const id = principal.id;\n const user = principal.role === 'admin' ? null : await User.findUnique({ where: { id } });\n if (user?.refreshToken) await updateSecurity(User, { id, refreshToken: user.refreshToken }, { refreshToken: '', refreshTokenExpiry: new Date(0) });\n const admin = principal.role === 'admin' ? await Admin.findUnique({ where: { id } }) : null;\n if (admin?.refreshToken) await updateSecurity(Admin, { id, refreshToken: admin.refreshToken }, { refreshToken: '', refreshTokenExpiry: new Date(0) });\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.js","content":"import { requireAuth } from 'express-file-cluster/auth';\nexport const meta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req, res) => {\n res.json({ user: req.user });\n};\n"},{"path":"src/api/auth/register.js","content":"import { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nexport const meta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req, res) => {\n const { name, email, password } = req.body;\n // 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, twoFactorSecret: _tfs, twoFactorPendingSecret: _tfp, twoFactorPendingExpiry: _tfpe, twoFactorLastStep: _tfl, twoFactorEmailHash: _tfeh, twoFactorEmailExpiry: _tfee, twoFactorEmailPurpose: _tfep, twoFactorPendingMethod: _tfpm, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/lib/two-factor.js","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { enqueue } from 'express-file-cluster/tasks';\n\n\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\nexport function newSecret() {\n const bytes = crypto.randomBytes(20);\n let bits = 0, value = 0, result = '';\n for (const byte of bytes) {\n value = (value << 8) | byte; bits += 8;\n while (bits >= 5) { bits -= 5; result += ALPHABET[(value >>> bits) & 31]; }\n }\n return result;\n}\nfunction secretBytes(secret) {\n if (!/^[A-Z2-7]+$/.test(secret)) throw new Error('Invalid TOTP secret');\n let bits = 0, value = 0;\n const bytes = [];\n for (const char of secret) {\n value = (value << 5) | ALPHABET.indexOf(char); bits += 5;\n if (bits >= 8) { bits -= 8; bytes.push((value >>> bits) & 255); }\n }\n return Buffer.from(bytes);\n}\n// RFC 6238: SHA-1, six digits, 30-second steps, one step of clock drift.\nexport function totp(secret, step) {\n const counter = Buffer.alloc(8);\n counter.writeBigUInt64BE(BigInt(step));\n const digest = crypto.createHmac('sha1', secretBytes(secret)).update(counter).digest();\n const offset = digest[digest.length - 1] & 15;\n return String((digest.readUInt32BE(offset) & 0x7fffffff) % 1000000).padStart(6, '0');\n}\nexport function codeStep(secret, code, last = -1, now = Date.now()) {\n if (typeof code !== 'string' || !/^\\d{6}$/.test(code)) return undefined;\n const step = Math.floor(now / 30000);\n for (const candidate of [step, step - 1, step + 1]) {\n if (candidate > last && candidate >= 0 && crypto.timingSafeEqual(Buffer.from(code), Buffer.from(totp(secret, candidate)))) return candidate;\n }\n return undefined;\n}\nfunction encryptionKey() {\n const key = process.env.TWO_FACTOR_KEY;\n if (!key || !/^[a-fA-F0-9]{64}$/.test(key)) throw new HttpError(503, 'TWO_FACTOR_KEY must be 32 random bytes encoded as 64 hex characters');\n return Buffer.from(key, 'hex');\n}\nexport function sealSecret(secret, identity) {\n const iv = crypto.randomBytes(12);\n const cipher = crypto.createCipheriv('aes-256-gcm', encryptionKey(), iv);\n cipher.setAAD(Buffer.from(identity));\n const encrypted = Buffer.concat([cipher.update(secret, 'utf8'), cipher.final()]);\n return Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString('base64url');\n}\nexport function openSecret(encrypted, identity) {\n const key = encryptionKey();\n try {\n const data = Buffer.from(encrypted, 'base64url');\n const decipher = crypto.createDecipheriv('aes-256-gcm', key, data.subarray(0, 12));\n decipher.setAAD(Buffer.from(identity));\n decipher.setAuthTag(data.subarray(12, 28));\n return Buffer.concat([decipher.update(data.subarray(28)), decipher.final()]).toString('utf8');\n } catch { throw new HttpError(503, 'Two-factor secret could not be decrypted'); }\n}\nexport async function updateSecurity(model, where, data) {\n const result = await model.updateMany({ where, data });\n return result.count === 1;\n}\nexport function allowedMethods() {\n const value = process.env.TWO_FACTOR_METHOD ?? 'totp';\n if (!['totp', 'email', 'both'].includes(value)) throw new HttpError(503, 'Invalid TWO_FACTOR_METHOD');\n return value === 'both' ? ['totp', 'email'] : [value];\n}\nfunction emailDigest(identity, purpose, code) {\n return crypto.createHmac('sha256', encryptionKey()).update(identity + ':' + purpose + ':' + code).digest('hex');\n}\nexport async function sendEmailCode(model, account, kind, purpose) {\n if (!process.env.SMTP_HOST) throw new HttpError(503, 'Configure the email-client SMTP settings before using email OTP');\n const code = String(crypto.randomInt(0, 1000000)).padStart(6, '0');\n const twoFactorEmailHash = emailDigest(kind + ':' + account.id + ':' + account.email, purpose, code);\n const updated = await updateSecurity(model, { id: account.id, twoFactorEnabled: !!account.twoFactorEnabled }, {\n twoFactorEmailHash, twoFactorEmailExpiry: new Date(Date.now() + 300000), twoFactorEmailPurpose: purpose,\n });\n if (!updated) throw new HttpError(409, 'Account security changed; try again');\n try {\n await enqueue('SendEmail', { to: account.email, subject: 'Your EFC verification code', body: 'Your verification code is <b>' + code + '</b>. It expires in 5 minutes.' });\n } catch (error) {\n await updateSecurity(model, { id: account.id, twoFactorEmailHash }, { twoFactorEmailHash: '' });\n throw error;\n }\n}\nexport async function consumeEmailCode(model, account, kind, purpose, code) {\n if (typeof code !== 'string' || !/^\\d{6}$/.test(code) || !account.twoFactorEmailHash || account.twoFactorEmailPurpose !== purpose || !account.twoFactorEmailExpiry || new Date(account.twoFactorEmailExpiry).getTime() <= Date.now()) return false;\n const digest = emailDigest(kind + ':' + account.id + ':' + account.email, purpose, code);\n const stored = Buffer.from(account.twoFactorEmailHash, 'hex');\n const supplied = Buffer.from(digest, 'hex');\n if (stored.length !== supplied.length || !crypto.timingSafeEqual(stored, supplied)) return false;\n return updateSecurity(model, { id: account.id, twoFactorEmailHash: account.twoFactorEmailHash, twoFactorEnabled: !!account.twoFactorEnabled }, { twoFactorEmailHash: '', twoFactorEmailExpiry: new Date(0) });\n}\nexport async function acceptTwoFactor(model, account, kind, code, purpose = 'login') {\n if (!account.twoFactorEnabled) return true;\n const method = account.twoFactorMethod ?? 'totp';\n if (!allowedMethods().includes(method)) return false;\n if (method === 'email') {\n if (code === undefined) { await sendEmailCode(model, account, kind, purpose); return false; }\n return consumeEmailCode(model, account, kind, purpose, code);\n }\n if (!account.twoFactorSecret) return false;\n const step = codeStep(openSecret(account.twoFactorSecret, kind + ':' + account.id), code, account.twoFactorLastStep ?? -1);\n if (step === undefined) return false;\n // Compare-and-set in the database: only one worker can accept a given code.\n return updateSecurity(model, { id: account.id, twoFactorEnabled: true, twoFactorSecret: account.twoFactorSecret, twoFactorLastStep: { lt: step } }, { twoFactorLastStep: step });\n}\n"},{"path":"src/model/Admin.js","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 twoFactorEnabled: { type: 'boolean', default: false },\n twoFactorSecret: { type: 'string', default: '' },\n twoFactorLastStep: { type: 'number', default: -1 },\n twoFactorPendingSecret: { type: 'string', default: '' },\n twoFactorPendingExpiry: { type: 'date' },\n twoFactorMethod: { type: 'string', default: '' },\n twoFactorPendingMethod: { type: 'string', default: '' },\n twoFactorEmailHash: { type: 'string', default: '' },\n twoFactorEmailExpiry: { type: 'date' },\n twoFactorEmailPurpose: { type: 'string', default: '' },\n});\n"},{"path":"src/model/User.js","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 twoFactorEnabled: { type: 'boolean', default: false },\n twoFactorSecret: { type: 'string', default: '' },\n twoFactorLastStep: { type: 'number', default: -1 },\n twoFactorPendingSecret: { type: 'string', default: '' },\n twoFactorPendingExpiry: { type: 'date' },\n twoFactorMethod: { type: 'string', default: '' },\n twoFactorPendingMethod: { type: 'string', default: '' },\n twoFactorEmailHash: { type: 'string', default: '' },\n twoFactorEmailExpiry: { type: 'date' },\n twoFactorEmailPurpose: { type: 'string', default: '' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}