express-file-cluster 0.9.3 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/index.cjs +6 -7
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +7 -2
- package/dist/auth/index.d.ts +7 -2
- package/dist/auth/index.js +5 -6
- package/dist/{chunk-QL6EWT4B.cjs → chunk-4DOHQU6I.cjs} +9 -7
- package/dist/chunk-4DOHQU6I.cjs.map +1 -0
- package/dist/chunk-73XJUT2S.js +366 -0
- package/dist/chunk-73XJUT2S.js.map +1 -0
- package/dist/{chunk-ATL4GYFU.js → chunk-7KC2H76D.js} +50 -8
- package/dist/chunk-7KC2H76D.js.map +1 -0
- package/dist/{chunk-TYR2GZZE.cjs → chunk-7KO4DJRJ.cjs} +19 -14
- package/dist/chunk-7KO4DJRJ.cjs.map +1 -0
- package/dist/{chunk-UBQYQPBU.js → chunk-ATVD2HGC.js} +4 -4
- package/dist/{chunk-R34R7QPD.cjs → chunk-DCJOWFVD.cjs} +3 -3
- package/dist/{chunk-R34R7QPD.cjs.map → chunk-DCJOWFVD.cjs.map} +1 -1
- package/dist/chunk-DUADUR6R.cjs +366 -0
- package/dist/chunk-DUADUR6R.cjs.map +1 -0
- package/dist/{chunk-BBSZLGZW.js → chunk-EGSSZUVO.js} +8 -6
- package/dist/chunk-EGSSZUVO.js.map +1 -0
- package/dist/{chunk-TI24L4XE.cjs → chunk-GBI77W5T.cjs} +6 -2
- package/dist/chunk-GBI77W5T.cjs.map +1 -0
- package/dist/{chunk-RTF7PHS2.cjs → chunk-HBCY7ILD.cjs} +306 -119
- package/dist/chunk-HBCY7ILD.cjs.map +1 -0
- package/dist/{chunk-ANUSWEAP.cjs → chunk-KFVFP2Q7.cjs} +59 -17
- package/dist/chunk-KFVFP2Q7.cjs.map +1 -0
- package/dist/{chunk-RS4MXCPW.js → chunk-NI2BNGGV.js} +2 -2
- package/dist/{chunk-X2US4RAM.cjs → chunk-NKLOE4AK.cjs} +11 -13
- package/dist/chunk-NKLOE4AK.cjs.map +1 -0
- package/dist/{chunk-RRQ2RK5M.js → chunk-PGJQK36V.js} +195 -8
- package/dist/chunk-PGJQK36V.js.map +1 -0
- package/dist/{chunk-QKQZF573.js → chunk-QDEDOHP7.js} +4 -6
- package/dist/chunk-QDEDOHP7.js.map +1 -0
- package/dist/{chunk-UTM4PEVG.js → chunk-R4XO4SVM.js} +10 -5
- package/dist/chunk-R4XO4SVM.js.map +1 -0
- package/dist/chunk-R52CUEGT.js +74 -0
- package/dist/chunk-R52CUEGT.js.map +1 -0
- package/dist/{chunk-HBYSKULC.js → chunk-RAB44UGX.js} +5 -1
- package/dist/chunk-RAB44UGX.js.map +1 -0
- package/dist/{chunk-7YEX4MQV.cjs → chunk-WBLUGOAG.cjs} +42 -6
- package/dist/chunk-WBLUGOAG.cjs.map +1 -0
- package/dist/{chunk-T4OHFU5T.cjs → chunk-YK4ZM3CA.cjs} +15 -15
- package/dist/{chunk-T4OHFU5T.cjs.map → chunk-YK4ZM3CA.cjs.map} +1 -1
- package/dist/cli/db-runner.cjs +2012 -120
- package/dist/cli/db-runner.cjs.map +1 -1
- package/dist/cli/db-runner.js +1989 -97
- package/dist/cli/db-runner.js.map +1 -1
- package/dist/cli/index.cjs +101 -43
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +80 -22
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +10 -8
- package/dist/docs/api-reference/collection.md +44 -1
- package/dist/docs/api-reference/ignite.md +22 -3
- package/dist/docs/api-reference/types.md +99 -0
- package/dist/docs/cli/add.md +1 -1
- package/dist/docs/cli/db.md +2 -2
- package/dist/docs/contributing/index.md +1 -1
- package/dist/docs/core-concepts/background-tasks.md +6 -3
- package/dist/docs/getting-started/index.md +3 -2
- package/dist/docs/guides/authentication.md +34 -24
- package/dist/docs/guides/caching.md +32 -1
- package/dist/docs/guides/database.md +14 -0
- package/dist/docs/guides/feature-matrix.md +58 -0
- package/dist/docs/guides/migrations.md +23 -2
- package/dist/docs/guides/oauth.md +15 -1
- package/dist/docs/guides/which-api.md +2 -2
- package/dist/docs/index.md +4 -1
- package/dist/docs/skills/SKILL.md +2 -2
- package/dist/docs/skills/api-surface.md +10 -4
- package/dist/docs/skills/auth-internals.md +3 -3
- package/dist/docs/skills/tasks-internals.md +4 -3
- package/dist/docs/skills/what-not-to-invent.md +4 -3
- package/dist/docs/versioning.md +42 -0
- package/dist/index.cjs +144 -51
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +204 -3
- package/dist/index.d.ts +204 -3
- package/dist/index.js +107 -14
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-FW42SBSM.js +14 -0
- package/dist/pgboss-backend-RVHUBJTU.cjs +14 -0
- package/dist/{pgboss-backend-TCHI7CHM.cjs.map → pgboss-backend-RVHUBJTU.cjs.map} +1 -1
- package/dist/registry/index.json +34 -3
- package/dist/registry/js-mongo/account-security.json +1 -1
- package/dist/registry/js-mongo/admin-users.json +1 -1
- package/dist/registry/js-mongo/auth.json +1 -1
- package/dist/registry/js-mongo/auth@apple.json +1 -1
- package/dist/registry/js-mongo/auth@google.json +1 -1
- package/dist/registry/js-mongo/email-verification.json +1 -1
- package/dist/registry/js-mongo/forgot-password.json +1 -1
- package/dist/registry/js-mongo/user-profile.json +1 -1
- package/dist/registry/js-mongo-collection/_base.json +1 -0
- package/dist/registry/js-mongo-collection/account-security.json +1 -0
- package/dist/registry/js-mongo-collection/account-settings.json +1 -0
- package/dist/registry/js-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/js-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/js-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/js-mongo-collection/admin-content.json +1 -0
- package/dist/registry/js-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/js-mongo-collection/admin-support.json +1 -0
- package/dist/registry/js-mongo-collection/admin-system.json +1 -0
- package/dist/registry/js-mongo-collection/admin-users.json +1 -0
- package/dist/registry/js-mongo-collection/admin.json +1 -0
- package/dist/registry/js-mongo-collection/auth.json +1 -0
- package/dist/registry/js-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/js-mongo-collection/auth@google.json +1 -0
- package/dist/registry/js-mongo-collection/billing.json +1 -0
- package/dist/registry/js-mongo-collection/email-client.json +1 -0
- package/dist/registry/js-mongo-collection/email-verification.json +1 -0
- package/dist/registry/js-mongo-collection/files.json +1 -0
- package/dist/registry/js-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/js-mongo-collection/notifications.json +1 -0
- package/dist/registry/js-mongo-collection/support.json +1 -0
- package/dist/registry/js-mongo-collection/user-profile.json +1 -0
- package/dist/registry/js-pg-model/account-security.json +1 -1
- package/dist/registry/js-pg-model/admin-users.json +1 -1
- package/dist/registry/js-pg-model/auth.json +1 -1
- package/dist/registry/js-pg-model/auth@apple.json +1 -1
- package/dist/registry/js-pg-model/auth@google.json +1 -1
- package/dist/registry/js-pg-model/email-verification.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.json +1 -1
- package/dist/registry/js-pg-model/user-profile.json +1 -1
- package/dist/registry/js-pg-table/account-security.json +1 -1
- package/dist/registry/js-pg-table/admin-users.json +1 -1
- package/dist/registry/js-pg-table/auth.json +1 -1
- package/dist/registry/js-pg-table/auth@apple.json +1 -1
- package/dist/registry/js-pg-table/auth@google.json +1 -1
- package/dist/registry/js-pg-table/email-verification.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.json +1 -1
- package/dist/registry/js-pg-table/user-profile.json +1 -1
- package/dist/registry/ts-mongo/account-security.json +1 -1
- package/dist/registry/ts-mongo/admin-users.json +1 -1
- package/dist/registry/ts-mongo/auth.json +1 -1
- package/dist/registry/ts-mongo/auth@apple.json +1 -1
- package/dist/registry/ts-mongo/auth@google.json +1 -1
- package/dist/registry/ts-mongo/email-verification.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.json +1 -1
- package/dist/registry/ts-mongo/user-profile.json +1 -1
- package/dist/registry/ts-mongo-collection/_base.json +1 -0
- package/dist/registry/ts-mongo-collection/account-security.json +1 -0
- package/dist/registry/ts-mongo-collection/account-settings.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-admins.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-analytics.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-billing.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-content.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-logs.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-support.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-system.json +1 -0
- package/dist/registry/ts-mongo-collection/admin-users.json +1 -0
- package/dist/registry/ts-mongo-collection/admin.json +1 -0
- package/dist/registry/ts-mongo-collection/auth.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@apple.json +1 -0
- package/dist/registry/ts-mongo-collection/auth@google.json +1 -0
- package/dist/registry/ts-mongo-collection/billing.json +1 -0
- package/dist/registry/ts-mongo-collection/email-client.json +1 -0
- package/dist/registry/ts-mongo-collection/email-verification.json +1 -0
- package/dist/registry/ts-mongo-collection/files.json +1 -0
- package/dist/registry/ts-mongo-collection/forgot-password.json +1 -0
- package/dist/registry/ts-mongo-collection/notifications.json +1 -0
- package/dist/registry/ts-mongo-collection/support.json +1 -0
- package/dist/registry/ts-mongo-collection/user-profile.json +1 -0
- package/dist/registry/ts-pg-model/account-security.json +1 -1
- package/dist/registry/ts-pg-model/admin-users.json +1 -1
- package/dist/registry/ts-pg-model/auth.json +1 -1
- package/dist/registry/ts-pg-model/auth@apple.json +1 -1
- package/dist/registry/ts-pg-model/auth@google.json +1 -1
- package/dist/registry/ts-pg-model/email-verification.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.json +1 -1
- package/dist/registry/ts-pg-model/user-profile.json +1 -1
- package/dist/registry/ts-pg-table/account-security.json +1 -1
- package/dist/registry/ts-pg-table/admin-users.json +1 -1
- package/dist/registry/ts-pg-table/auth.json +1 -1
- package/dist/registry/ts-pg-table/auth@apple.json +1 -1
- package/dist/registry/ts-pg-table/auth@google.json +1 -1
- package/dist/registry/ts-pg-table/email-verification.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/dist/registry/ts-pg-table/user-profile.json +1 -1
- package/dist/tasks/index.cjs +4 -2
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +4 -2
- package/dist/tasks/index.d.ts +4 -2
- package/dist/tasks/index.js +3 -1
- package/dist/thread-runner.cjs +8 -0
- package/dist/thread-runner.cjs.map +1 -0
- package/dist/thread-runner.d.cts +3 -0
- package/dist/thread-runner.d.ts +3 -0
- package/dist/thread-runner.js +8 -0
- package/dist/thread-runner.js.map +1 -0
- package/dist/{types-BY-ObnZH.d.ts → types-Bnxvj3l0.d.cts} +14 -2
- package/dist/{types-BY-ObnZH.d.cts → types-Bnxvj3l0.d.ts} +14 -2
- package/package.json +1 -1
- package/dist/chunk-277BSYVH.js +0 -127
- package/dist/chunk-277BSYVH.js.map +0 -1
- package/dist/chunk-7YEX4MQV.cjs.map +0 -1
- package/dist/chunk-ANUSWEAP.cjs.map +0 -1
- package/dist/chunk-ATL4GYFU.js.map +0 -1
- package/dist/chunk-BBSZLGZW.js.map +0 -1
- package/dist/chunk-HBYSKULC.js.map +0 -1
- package/dist/chunk-HXV543HZ.js +0 -177
- package/dist/chunk-HXV543HZ.js.map +0 -1
- package/dist/chunk-LJNSJFOL.js +0 -38
- package/dist/chunk-LJNSJFOL.js.map +0 -1
- package/dist/chunk-QKQZF573.js.map +0 -1
- package/dist/chunk-QL6EWT4B.cjs.map +0 -1
- package/dist/chunk-RRQ2RK5M.js.map +0 -1
- package/dist/chunk-RTF7PHS2.cjs.map +0 -1
- package/dist/chunk-TI24L4XE.cjs.map +0 -1
- package/dist/chunk-TYR2GZZE.cjs.map +0 -1
- package/dist/chunk-UTM4PEVG.js.map +0 -1
- package/dist/chunk-VQSWSYK6.cjs +0 -177
- package/dist/chunk-VQSWSYK6.cjs.map +0 -1
- package/dist/chunk-X2US4RAM.cjs.map +0 -1
- package/dist/chunk-YL37D6KM.cjs +0 -127
- package/dist/chunk-YL37D6KM.cjs.map +0 -1
- package/dist/pgboss-backend-QKBXVJ6B.js +0 -14
- package/dist/pgboss-backend-TCHI7CHM.cjs +0 -14
- /package/dist/{chunk-UBQYQPBU.js.map → chunk-ATVD2HGC.js.map} +0 -0
- /package/dist/{chunk-RS4MXCPW.js.map → chunk-NI2BNGGV.js.map} +0 -0
- /package/dist/{pgboss-backend-QKBXVJ6B.js.map → pgboss-backend-FW42SBSM.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: '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: Request, res: Response) => {\n const token = req.cookies?.['efc_refresh_token'] || req.body?.refreshToken;\n if (!token) return res.status(401).json({ error: 'Refresh token required' });\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\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 await issueToken(res, { id: account.id, role: account.role, email: account.email });\n res.json({
|
|
1
|
+
{"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: '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: Request, res: Response) => {\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].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\n // TODO: fetch sessions for req.user.id\n res.json({ sessions: [] });\n};\n"},{"path":"src/model/Session.ts","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 +1 @@
|
|
|
1
|
-
{"name":"admin-users","files":[{"path":"src/api/admin/users/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch 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: Request, res: Response) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update(id, { name, email, role, isActive });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = updated;\n res.json({ message: 'User updated', user: safe });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\n const { id } = req.params;\n const { reason } = req.body;\n // TODO: set user.isActive = false, log audit event\n res.json({ message: `User ${id} suspended`, reason });\n};\n"},{"path":"src/api/admin/users/[id]/verify.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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.ts","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\n const page = Math.max(1, Number(req.query.page) || 1);\n const limit = Math.min(100, Number(req.query.limit) || 20);\n const [all, total] = await Promise.all([User.find({}), User.count({})]);\n const users = all.slice((page - 1) * limit, page * limit).map(({ password: _, ...u }) => u);\n res.json({ users, total, page, limit });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, email, password, role } = req.body;\n if (!name || !email || !password) return res.status(400).json({ error: 'name, email and password are required' });\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const user = await User.create({ name, email, password: hashed, role: role ?? 'user' });\n const { password: _, ...safe } = user;\n res.status(201).json({ message: 'User created', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
1
|
+
{"name":"admin-users","files":[{"path":"src/api/admin/users/[id].ts","content":"import { requireAuth, revokeAllSessions } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch 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: Request, res: Response) => {\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: Request, res: Response) => {\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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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.ts","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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: Request, res: Response) => {\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 +1 @@
|
|
|
1
|
-
{"name":"auth","files":[{"path":"src/api/auth/login.ts","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(\n res: Response,\n model: { update: (id: string, data: Record<string, unknown>) => Promise<unknown> },\n id: string,\n): Promise<
|
|
1
|
+
{"name":"auth","files":[{"path":"src/api/auth/login.ts","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\n// 10 attempts per 15 minutes per address and account. Keyed on the email too, so behind a\n// proxy without TRUST_PROXY (every client then has the proxy's IP) it still limits one\n// account at a time, never everyone.\nexport const middlewares = [\n rateLimit({\n window: '15m',\n max: 10,\n key: (req) => `${req.ip}:${String(req.body?.email ?? '').toLowerCase()}`,\n }),\n];\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(\n res: Response,\n model: { update: (id: string, data: Record<string, unknown>) => Promise<unknown> },\n id: string,\n): Promise<string> {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(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: Request, res: Response) => {\n const { email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {\n return res.status(400).json({ error: 'email and password are required' });\n }\n\n const admin = await Admin.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.ts","content":"import { revokeSession } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n res.json({ user: (req as any).user });\n};\n"},{"path":"src/api/auth/register.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof name !== 'string' || typeof email !== 'string' || typeof password !== 'string' || !name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.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.ts","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.ts","content":"import { defineModel } from 'express-file-cluster';\n\nexport const User = defineModel('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret(): Promise<string> {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name: string | undefined;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.ts","content":"import type { Request, Response } from 'express';\nimport { randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req: Request, res: Response) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<void> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect(): string {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.ts","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.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret(): Promise<string> {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name: string | undefined;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n const token = await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/apple/index.ts","content":"import type { Request, Response } from 'express';\nimport { appChallengeFrom, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req: Request, res: Response) => {\n const appChallenge = appChallengeFrom(req.query);\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce, ...(appChallenge ? { appChallenge } : {}) }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/api/auth/oauth/exchange.ts","content":"import type { Request, Response } from 'express';\nimport { exchangeCode } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Bearer apps: trade the one-time code from the sign-in redirect (plus the PKCE code_verifier) for a token.' },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n /** Bearer apps: the S256 challenge of a verifier only the app knows (app ↔ this server). */\n appChallenge?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<string | undefined> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.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: Request['query']): string | undefined {\n const challenge = query.code_challenge;\n if (challenge === undefined) return undefined;\n if (typeof challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n throw new HttpError(400, 'code_challenge must be the base64url SHA-256 of your code_verifier');\n }\n return challenge;\n}\n\n/**\n * Where the browser goes once signed in. With authStrategy 'bearer' the JWT never goes in the\n * URL (history, screenshots, logs): it gets a one-time code, valid for a minute, which the app\n * that started the sign-in trades for the token at POST /auth/oauth/exchange.\n */\nexport async function successRedirect(\n token?: string,\n appChallenge?: string,\n): Promise<string> {\n const to = process.env.OAUTH_SUCCESS_REDIRECT || '/';\n if (!token) return to;\n if (!appChallenge) {\n throw new HttpError(\n 400,\n 'Bearer sign-in needs a code_challenge — start at /auth/<provider>?code_challenge=…',\n );\n }\n const code = randomToken();\n await cache.set(`oauth:code:${code}`, { token, appChallenge }, { ttl: CODE_TTL_S });\n return `${to}#code=${code}`;\n}\n\n/**\n * The token for a one-time sign-in code, given the verifier behind the challenge the sign-in\n * started with. Once: a second use (or after a minute) gets 400.\n */\nexport async function exchangeCode(code: unknown, verifier: unknown): Promise<string> {\n if (typeof code !== 'string' || !code) throw new HttpError(400, 'code is required');\n if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {\n throw new HttpError(400, 'code_verifier is required (43-128 characters)');\n }\n const key = `oauth:code:${code}`;\n const saved = await cache.get<{ token: string; appChallenge: string }>(key);\n const expected = Buffer.from(saved?.appChallenge ?? '');\n const actual = Buffer.from(pkceChallenge(verifier));\n // A wrong verifier leaves the code alone, so it can't be used to burn someone's sign-in.\n if (!saved || expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {\n throw new HttpError(400, 'Invalid or expired sign-in code');\n }\n // del is atomic: of two requests racing with the same code, only one removes it.\n if ((await cache.del(key)) !== 1) throw new HttpError(400, 'Invalid or expired sign-in code');\n return saved.token;\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { 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.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req: Request, res: Response) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true,\n name: payload.name as string | undefined,\n });\n res.redirect(successRedirect());\n};\n"},{"path":"src/api/auth/google/index.ts","content":"import type { Request, Response } from 'express';\nimport { pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\nexport const GET = async (_req: Request, res: Response) => {\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<void> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findOne({ key });\n let user = account ? await User.findById(account.userId) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findOne({ email })) ??\n (await User.create({\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n }));\n if (account) await OAuthAccount.update(account.id, { userId: user.id });\n else {\n await OAuthAccount.create({\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n userId: user.id,\n });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect(): string {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.ts","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.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req: Request, res: Response) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n const token = await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true,\n name: payload.name as string | undefined,\n });\n res.redirect(await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/google/index.ts","content":"import type { Request, Response } from 'express';\nimport { appChallengeFrom, pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req: Request, res: Response) => {\n const appChallenge = appChallengeFrom(req.query);\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier, ...(appChallenge ? { appChallenge } : {}) });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/api/auth/oauth/exchange.ts","content":"import type { Request, Response } from 'express';\nimport { exchangeCode } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Bearer apps: trade the one-time code from the sign-in redirect (plus the PKCE code_verifier) for a token.' },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n /** Bearer apps: the S256 challenge of a verifier only the app knows (app ↔ this server). */\n appChallenge?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<string | undefined> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.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: Request['query']): string | undefined {\n const challenge = query.code_challenge;\n if (challenge === undefined) return undefined;\n if (typeof challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n throw new HttpError(400, 'code_challenge must be the base64url SHA-256 of your code_verifier');\n }\n return challenge;\n}\n\n/**\n * Where the browser goes once signed in. With authStrategy 'bearer' the JWT never goes in the\n * URL (history, screenshots, logs): it gets a one-time code, valid for a minute, which the app\n * that started the sign-in trades for the token at POST /auth/oauth/exchange.\n */\nexport async function successRedirect(\n token?: string,\n appChallenge?: string,\n): Promise<string> {\n const to = process.env.OAUTH_SUCCESS_REDIRECT || '/';\n if (!token) return to;\n if (!appChallenge) {\n throw new HttpError(\n 400,\n 'Bearer sign-in needs a code_challenge — start at /auth/<provider>?code_challenge=…',\n );\n }\n const code = randomToken();\n await cache.set(`oauth:code:${code}`, { token, appChallenge }, { ttl: CODE_TTL_S });\n return `${to}#code=${code}`;\n}\n\n/**\n * The token for a one-time sign-in code, given the verifier behind the challenge the sign-in\n * started with. Once: a second use (or after a minute) gets 400.\n */\nexport async function exchangeCode(code: unknown, verifier: unknown): Promise<string> {\n if (typeof code !== 'string' || !code) throw new HttpError(400, 'code is required');\n if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {\n throw new HttpError(400, 'code_verifier is required (43-128 characters)');\n }\n const key = `oauth:code:${code}`;\n const saved = await cache.get<{ token: string; appChallenge: string }>(key);\n const expected = Buffer.from(saved?.appChallenge ?? '');\n const actual = Buffer.from(pkceChallenge(verifier));\n // A wrong verifier leaves the code alone, so it can't be used to burn someone's sign-in.\n if (!saved || expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {\n throw new HttpError(400, 'Invalid or expired sign-in code');\n }\n // del is atomic: of two requests racing with the same code, only one removes it.\n if ((await cache.del(key)) !== 1) throw new HttpError(400, 'Invalid or expired sign-in code');\n return saved.token;\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineModel } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineModel('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n userId: { type: 'string', required: true },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"email-verification","files":[{"path":"src/api/auth/verify-email.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Verify an email address using the token from the verification link.',\n request: { query: { token: 'a1b2c3d4' } },\n response: { status: 200, body: { message: 'Email verified' } },\n },\n POST: {\n description: 'Resend the verification email to a given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Verification email sent' } },\n },\n};\n\nexport const GET = async (req: Request, res: Response) => {\n const { token } = req.query;\n if (!token || typeof token !== 'string') return res.status(400).json({ error: 'token is required' });\n\n const user = await User.findOne({ verifyToken: token });\n if (!user) return res.status(400).json({ error: 'Invalid or expired verification token' });\n\n await User.update(user.id, { isVerified: true, verifyToken: '' });\n res.json({ message: 'Email verified' });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n if (user && !user.isVerified) {\n const verifyToken = crypto.randomBytes(32).toString('hex');\n await User.update(user.id, { verifyToken });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n }\n\n res.json({ message: 'Verification email sent' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
1
|
+
{"name":"email-verification","files":[{"path":"src/api/auth/verify-email.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Verify an email address using the token from the verification link.',\n request: { query: { token: 'a1b2c3d4' } },\n response: { status: 200, body: { message: 'Email verified' } },\n },\n POST: {\n description: 'Resend the verification email to a given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Verification email sent' } },\n },\n};\n\nexport const GET = async (req: Request, res: Response) => {\n const { token } = req.query;\n if (!token || typeof token !== 'string') return res.status(400).json({ error: 'token is required' });\n\n const user = await User.findOne({ verifyToken: token });\n if (!user) return res.status(400).json({ error: 'Invalid or expired verification token' });\n\n await User.update(user.id, { isVerified: true, verifyToken: '' });\n res.json({ message: 'Email verified' });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findOne({ email });\n if (user && !user.isVerified) {\n const verifyToken = crypto.randomBytes(32).toString('hex');\n await User.update(user.id, { verifyToken });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n }\n\n res.json({ message: 'Verification email sent' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.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.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { token, password } = req.body;\n if (!token || !password) return res.status(400).json({ error: 'token and password are required' });\n\n const user = await User.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.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { rateLimit } from 'express-file-cluster';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\n// 5 reset emails per hour per address — keeps the endpoint from mail-bombing someone.\nexport const middlewares = [\n rateLimit({ window: '1h', max: 5, key: (req) => String(req.body?.email ?? '').toLowerCase() }),\n];\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || !email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.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.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { token, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof token !== 'string' || typeof password !== 'string' || !token || !password) {\n return res.status(400).json({ error: 'token and password are required' });\n }\n\n const user = await User.findOne({ resetToken: token });\n const admin = user ? null : await Admin.findOne({ resetToken: token });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n if (user) await User.update(user.id, { password: hashed, resetToken: '' });\n else if (admin) await Admin.update(admin.id, { password: hashed, resetToken: '' });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"user-profile","files":[{"path":"src/api/user/profile.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: \"Fetch the authenticated user's profile.\",\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n PUT: {\n description: \"Update the authenticated user's profile.\",\n request: { body: { name: 'Jane Doe', email: 'jane@example.com' } },\n response: { status: 200, body: { message: 'Profile updated', user: { id: '1', role: 'user', email: 'jane@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const user = await User.findById(id);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = (req as any).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: _, ...safe } = updated;\n res.json({ message: 'Profile updated', user: safe });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
1
|
+
{"name":"user-profile","files":[{"path":"src/api/user/profile.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: \"Fetch the authenticated user's profile.\",\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n PUT: {\n description: \"Update the authenticated user's profile.\",\n request: { body: { name: 'Jane Doe', email: 'jane@example.com' } },\n response: { status: 200, body: { message: 'Profile updated', user: { id: '1', role: 'user', email: 'jane@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = (req as any).user;\n const user = await User.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: Request, res: Response) => {\n const { id } = (req as any).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":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"files":[{"path":"src/api/health.ts","content":"import type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Health check — returns server status and current timestamp.',\n response: { status: 200, body: { status: 'OK', timestamp: '2024-01-01T00:00:00.000Z' } },\n },\n};\n\nexport const GET = async (_req: Request, res: Response) => {\n res.json({ status: 'OK', timestamp: new Date().toISOString() });\n};\n"},{"path":"src/tasks/SendEmail.ts","content":"import { defineTask } from 'express-file-cluster/tasks';\n\ninterface SendEmailPayload {\n to: string;\n subject: string;\n body: string;\n}\n\nexport default defineTask<SendEmailPayload>(async (payload) => {\n // TODO: wire up your mailer\n console.log('[SendEmail] Sending to', payload.to);\n});\n"}]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"account-security","files":[{"path":"src/api/auth/2fa/disable.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: '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: Request, res: Response) => {\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.findByIdAndUpdate(user.id, { refreshToken: newRefreshToken, refreshTokenExpiry }, { returnDocument: 'after' });\n else if (admin) await Admin.findByIdAndUpdate(admin.id, { refreshToken: newRefreshToken, refreshTokenExpiry }, { returnDocument: 'after' });\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].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\n // TODO: fetch sessions for req.user.id\n res.json({ sessions: [] });\n};\n"},{"path":"src/model/Session.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Session = defineCollection('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":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"account-settings","files":[{"path":"src/api/user/account.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Download a personal data export for the authenticated user.',\n response: { status: 200, body: { data: { user: { id: '1', role: 'user', email: 'user@example.com' }, exportedAt: '2026-01-01T00:00:00.000Z' } } },\n },\n DELETE: {\n description: 'Schedule the authenticated account for deletion (requires password confirmation).',\n request: { body: { password: 'current' } },\n response: { status: 200, body: { message: 'Account scheduled for deletion' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n // TODO: compile and return personal data export\n res.json({ data: { user: (req as any).user, exportedAt: new Date().toISOString() } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { password } = req.body;\n if (!password) return res.status(400).json({ error: 'password confirmation required' });\n // TODO: verify password, schedule account deletion\n res.json({ message: 'Account scheduled for deletion' });\n};\n"},{"path":"src/api/user/activity.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Paginated activity history for the authenticated user.',\n request: { query: { page: '1', limit: '20' } },\n response: { status: 200, body: { activities: [], total: 0, page: 1, limit: 20 } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { page = 1, limit = 20 } = req.query;\n // TODO: fetch paginated activity log\n res.json({ activities: [], total: 0, page: Number(page), limit: Number(limit) });\n};\n"},{"path":"src/api/user/avatar.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Upload a new avatar image for the authenticated user.',\n response: { status: 200, body: { message: 'Avatar updated', url: 'https://example.com/avatar.jpg' } },\n },\n DELETE: {\n description: 'Remove the authenticated user\\'s avatar.',\n response: { status: 200, body: { message: 'Avatar removed' } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const POST = async (req: Request, res: Response) => {\n // TODO: handle multipart upload, store file, update user.avatar\n res.json({ message: 'Avatar updated', url: 'https://example.com/avatar.jpg' });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n // TODO: remove avatar and clear user.avatar\n res.json({ message: 'Avatar removed' });\n};\n"},{"path":"src/api/user/dashboard.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Personal dashboard: stats, recent activity, and quick actions.',\n response: { status: 200, body: { stats: {}, recentActivity: [], quickActions: [] } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n // TODO: aggregate personal stats and activity\n res.json({ stats: {}, recentActivity: [], quickActions: [] });\n};\n"},{"path":"src/api/user/settings.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Get account settings (notifications, language, theme, privacy) for the authenticated user.',\n response: { status: 200, body: { settings: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } } },\n },\n PUT: {\n description: 'Update account settings for the authenticated user.',\n request: { body: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } },\n response: { status: 200, body: { message: 'Settings updated', settings: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n // TODO: fetch user settings from DB\n res.json({ settings: { notifications: true, language: 'en', theme: 'system', privacy: 'public' } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { notifications, language, theme, privacy } = req.body;\n // TODO: update user settings in DB\n res.json({ message: 'Settings updated', settings: { notifications, language, theme, privacy } });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-admins","files":[{"path":"src/api/admin/admins/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single admin account by ID (admin only).',\n request: { params: { id: 'adm_01HXZ' } },\n response: { status: 200, body: { admin: { id: 'adm_01HXZ' } } },\n },\n PUT: {\n description: 'Update an admin account by ID (admin only).',\n request: { params: { id: 'adm_01HXZ' }, body: { name: 'Jane Doe', role: 'admin' } },\n response: { status: 200, body: { message: 'Admin updated', admin: { id: 'adm_01HXZ', name: 'Jane Doe', role: 'admin' } } },\n },\n DELETE: {\n description: 'Delete an admin account by ID (admin only).',\n request: { params: { id: 'adm_01HXZ' } },\n response: { status: 200, body: { message: 'Admin adm_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch admin by id\n res.json({ admin: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: update admin record\n res.json({ message: 'Admin updated', admin: { id, ...req.body } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: delete admin\n res.json({ message: `Admin ${id} deleted` });\n};\n"},{"path":"src/api/admin/admins/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all admin accounts (admin only).',\n response: { status: 200, body: { admins: [], total: 0 } },\n },\n POST: {\n description: 'Create a new admin account (admin only).',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', role: 'admin' } },\n response: { status: 201, body: { message: 'Admin created', admin: { id: 'new-id', name: 'Jane Doe', email: 'jane@example.com', role: 'admin' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch admins from DB\n res.json({ admins: [], total: 0 });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, email, role } = req.body;\n if (!name || !email) return res.status(400).json({ error: 'name and email are required' });\n // TODO: create admin account\n res.status(201).json({ message: 'Admin created', admin: { id: 'new-id', name, email, role: role ?? 'admin' } });\n};\n"},{"path":"src/api/admin/roles/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single role by ID (admin only).',\n request: { params: { id: 'role_01HXZ' } },\n response: { status: 200, body: { role: { id: 'role_01HXZ', name: 'editor', permissions: ['content:write'] } } },\n },\n PUT: {\n description: 'Update a role by ID (admin only).',\n request: { params: { id: 'role_01HXZ' }, body: { name: 'editor', permissions: ['content:write'] } },\n response: { status: 200, body: { message: 'Role updated', role: { id: 'role_01HXZ', name: 'editor', permissions: ['content:write'] } } },\n },\n DELETE: {\n description: 'Delete a role by ID (admin only).',\n request: { params: { id: 'role_01HXZ' } },\n response: { status: 200, body: { message: 'Role role_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch role by id\n res.json({ role: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: update role\n res.json({ message: 'Role updated', role: { id, ...req.body } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: delete role\n res.json({ message: `Role ${id} deleted` });\n};\n"},{"path":"src/api/admin/roles/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all roles (admin only).',\n response: { status: 200, body: { roles: [] } },\n },\n POST: {\n description: 'Create a new role (admin only).',\n request: { body: { name: 'editor', description: 'Can edit content', permissions: ['content:write'] } },\n response: { status: 201, body: { message: 'Role created', role: { id: 'new-id', name: 'editor', permissions: ['content:write'] } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch all roles\n res.json({ roles: [] });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, description, permissions } = req.body;\n if (!name) return res.status(400).json({ error: 'name is required' });\n // TODO: create role\n res.status(201).json({ message: 'Role created', role: { id: 'new-id', name, permissions: permissions ?? [] } });\n};\n"},{"path":"src/model/Role.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Role = defineCollection('Role', {\n name: { type: 'string', required: true, unique: true },\n description: { type: 'string', required: true },\n permissions: { type: 'array', of: 'string', default: [] },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-analytics","files":[{"path":"src/api/admin/analytics/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Analytics overview: users, revenue, traffic (admin only).',\n response: { status: 200, body: { users: {}, revenue: {}, traffic: {} } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n // TODO: aggregate analytics overview\n res.json({ users: {}, revenue: {}, traffic: {} });\n};\n"},{"path":"src/api/admin/analytics/revenue.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Revenue analytics: MRR, ARR, payment history (admin only).',\n request: { query: { period: '30d' } },\n response: { status: 200, body: { mrr: 0, arr: 0, history: [], period: '30d' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { period = '30d' } = req.query;\n // TODO: fetch revenue analytics for period\n res.json({ mrr: 0, arr: 0, history: [], period });\n};\n"},{"path":"src/api/admin/analytics/traffic.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Traffic analytics: page views, devices, countries (admin only).',\n request: { query: { period: '30d' } },\n response: { status: 200, body: { pageViews: 0, devices: {}, countries: {}, period: '30d' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { period = '30d' } = req.query;\n // TODO: fetch traffic analytics for period\n res.json({ pageViews: 0, devices: {}, countries: {}, period });\n};\n"},{"path":"src/api/admin/analytics/users.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'User analytics: registrations, active users, churn (admin only).',\n request: { query: { period: '30d' } },\n response: { status: 200, body: { registrations: [], activeUsers: 0, churn: 0, period: '30d' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { period = '30d' } = req.query;\n // TODO: fetch user analytics for period\n res.json({ registrations: [], activeUsers: 0, churn: 0, period });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-billing","files":[{"path":"src/api/admin/billing/coupons/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single coupon by ID (admin only).',\n request: { params: { id: 'coupon_01HXZ' } },\n response: { status: 200, body: { coupon: { id: 'coupon_01HXZ', code: 'sample-code', type: 'sample-type', value: 'sample-value' } } },\n },\n PUT: {\n description: 'Update a coupon by ID (admin only).',\n request: { params: { id: 'coupon_01HXZ' }, body: { code: 'sample-code', type: 'sample-type', value: 'sample-value' } },\n response: { status: 200, body: { message: 'Coupon updated', coupon: { id: 'coupon_01HXZ', code: 'sample-code', type: 'sample-type', value: 'sample-value' } } },\n },\n DELETE: {\n description: 'Delete a coupon by ID (admin only).',\n request: { params: { id: 'coupon_01HXZ' } },\n response: { status: 200, body: { message: 'Coupon coupon_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch Coupon by id\n res.json({ coupon: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: update Coupon\n res.json({ message: 'Coupon updated', coupon: { id, ...req.body } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: delete Coupon\n res.json({ message: `Coupon ${id} deleted` });\n};\n"},{"path":"src/api/admin/billing/coupons/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all coupons (admin only).',\n response: { status: 200, body: { coupons: [], total: 0 } },\n },\n POST: {\n description: 'Create a new coupon (admin only).',\n request: { body: { code: 'sample-code', type: 'sample-type', value: 'sample-value' } },\n response: { status: 201, body: { message: 'Coupon created', coupon: { id: 'new-id', code: 'sample-code' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch coupons\n res.json({ coupons: [], total: 0 });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { code, type, value } = req.body;\n // TODO: create Coupon\n res.status(201).json({ message: 'Coupon created', coupon: { id: 'new-id', code } });\n};\n"},{"path":"src/api/admin/billing/plans/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single plan by ID (admin only).',\n request: { params: { id: 'plan_01HXZ' } },\n response: { status: 200, body: { plan: { id: 'plan_01HXZ', name: 'sample-name', price: 'sample-price', interval: 'sample-interval' } } },\n },\n PUT: {\n description: 'Update a plan by ID (admin only).',\n request: { params: { id: 'plan_01HXZ' }, body: { name: 'sample-name', price: 'sample-price', interval: 'sample-interval' } },\n response: { status: 200, body: { message: 'Plan updated', plan: { id: 'plan_01HXZ', name: 'sample-name', price: 'sample-price', interval: 'sample-interval' } } },\n },\n DELETE: {\n description: 'Delete a plan by ID (admin only).',\n request: { params: { id: 'plan_01HXZ' } },\n response: { status: 200, body: { message: 'Plan plan_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch Plan by id\n res.json({ plan: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: update Plan\n res.json({ message: 'Plan updated', plan: { id, ...req.body } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: delete Plan\n res.json({ message: `Plan ${id} deleted` });\n};\n"},{"path":"src/api/admin/billing/plans/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all plans (admin only).',\n response: { status: 200, body: { plans: [], total: 0 } },\n },\n POST: {\n description: 'Create a new plan (admin only).',\n request: { body: { name: 'sample-name', price: 'sample-price', interval: 'sample-interval' } },\n response: { status: 201, body: { message: 'Plan created', plan: { id: 'new-id', name: 'sample-name' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch plans\n res.json({ plans: [], total: 0 });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, price, interval } = req.body;\n // TODO: create Plan\n res.status(201).json({ message: 'Plan created', plan: { id: 'new-id', name } });\n};\n"},{"path":"src/api/admin/billing/subscriptions/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all subscriptions with filters (admin only).',\n request: { query: { status: 'active', page: '1', limit: '20' } },\n response: { status: 200, body: { subscriptions: [], total: 0, page: 1, limit: 20 } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { status, page = 1, limit = 20 } = req.query;\n // TODO: fetch all subscriptions with filters\n res.json({ subscriptions: [], total: 0, page: Number(page), limit: Number(limit) });\n};\n"},{"path":"src/model/Coupon.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Coupon = defineCollection('Coupon', {\n code: { type: 'string', required: true, unique: true },\n type: { type: 'string', required: true, default: 'percent' },\n value: { type: 'number', required: true },\n maxUses: { type: 'number', default: 0 },\n usedCount: { type: 'number', default: 0 },\n expiresAt: { type: 'date' },\n isActive: { type: 'boolean', default: true },\n});\n"},{"path":"src/model/Plan.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Plan = defineCollection('Plan', {\n name: { type: 'string', required: true },\n description: { type: 'string', required: true },\n price: { type: 'number', required: true },\n interval: { type: 'string', required: true, default: 'monthly' },\n features: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-content","files":[{"path":"src/api/admin/content/blogs/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single blog by ID (admin only).',\n request: { params: { id: 'blog_01HXZ' } },\n response: { status: 200, body: { blog: { id: 'blog_01HXZ', title: 'sample-title', slug: 'sample-slug', content: 'sample-content' } } },\n },\n PUT: {\n description: 'Update a blog by ID (admin only).',\n request: { params: { id: 'blog_01HXZ' }, body: { title: 'sample-title', slug: 'sample-slug', content: 'sample-content' } },\n response: { status: 200, body: { message: 'Blog updated', blog: { id: 'blog_01HXZ', title: 'sample-title', slug: 'sample-slug', content: 'sample-content' } } },\n },\n DELETE: {\n description: 'Delete a blog by ID (admin only).',\n request: { params: { id: 'blog_01HXZ' } },\n response: { status: 200, body: { message: 'Blog blog_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch Blog by id\n res.json({ blog: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: update Blog\n res.json({ message: 'Blog updated', blog: { id, ...req.body } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: delete Blog\n res.json({ message: `Blog ${id} deleted` });\n};\n"},{"path":"src/api/admin/content/blogs/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all blogs (admin only).',\n response: { status: 200, body: { blogs: [], total: 0 } },\n },\n POST: {\n description: 'Create a new blog (admin only).',\n request: { body: { title: 'sample-title', slug: 'sample-slug', content: 'sample-content' } },\n response: { status: 201, body: { message: 'Blog created', blog: { id: 'new-id', title: 'sample-title' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch blogs\n res.json({ blogs: [], total: 0 });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { title, slug, content } = req.body;\n // TODO: create Blog\n res.status(201).json({ message: 'Blog created', blog: { id: 'new-id', title } });\n};\n"},{"path":"src/api/admin/content/categories/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single category by ID (admin only).',\n request: { params: { id: 'category_01HXZ' } },\n response: { status: 200, body: { category: { id: 'category_01HXZ', name: 'sample-name', slug: 'sample-slug' } } },\n },\n PUT: {\n description: 'Update a category by ID (admin only).',\n request: { params: { id: 'category_01HXZ' }, body: { name: 'sample-name', slug: 'sample-slug' } },\n response: { status: 200, body: { message: 'Category updated', category: { id: 'category_01HXZ', name: 'sample-name', slug: 'sample-slug' } } },\n },\n DELETE: {\n description: 'Delete a category by ID (admin only).',\n request: { params: { id: 'category_01HXZ' } },\n response: { status: 200, body: { message: 'Category category_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch Category by id\n res.json({ category: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: update Category\n res.json({ message: 'Category updated', category: { id, ...req.body } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: delete Category\n res.json({ message: `Category ${id} deleted` });\n};\n"},{"path":"src/api/admin/content/categories/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all categories (admin only).',\n response: { status: 200, body: { categories: [], total: 0 } },\n },\n POST: {\n description: 'Create a new category (admin only).',\n request: { body: { name: 'sample-name', slug: 'sample-slug' } },\n response: { status: 201, body: { message: 'Category created', category: { id: 'new-id', name: 'sample-name' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch categories\n res.json({ categories: [], total: 0 });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, slug } = req.body;\n // TODO: create Category\n res.status(201).json({ message: 'Category created', category: { id: 'new-id', name } });\n};\n"},{"path":"src/api/admin/content/faqs/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single faq by ID (admin only).',\n request: { params: { id: 'faq_01HXZ' } },\n response: { status: 200, body: { faq: { id: 'faq_01HXZ', question: 'sample-question', answer: 'sample-answer', category: 'sample-category' } } },\n },\n PUT: {\n description: 'Update a faq by ID (admin only).',\n request: { params: { id: 'faq_01HXZ' }, body: { question: 'sample-question', answer: 'sample-answer', category: 'sample-category' } },\n response: { status: 200, body: { message: 'FAQ updated', faq: { id: 'faq_01HXZ', question: 'sample-question', answer: 'sample-answer', category: 'sample-category' } } },\n },\n DELETE: {\n description: 'Delete a faq by ID (admin only).',\n request: { params: { id: 'faq_01HXZ' } },\n response: { status: 200, body: { message: 'FAQ faq_01HXZ deleted' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch FAQ by id\n res.json({ faq: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: update FAQ\n res.json({ message: 'FAQ updated', faq: { id, ...req.body } });\n};\n\nexport const DELETE = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: delete FAQ\n res.json({ message: `FAQ ${id} deleted` });\n};\n"},{"path":"src/api/admin/content/faqs/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all faqs (admin only).',\n response: { status: 200, body: { faqs: [], total: 0 } },\n },\n POST: {\n description: 'Create a new faq (admin only).',\n request: { body: { question: 'sample-question', answer: 'sample-answer', category: 'sample-category' } },\n response: { status: 201, body: { message: 'FAQ created', faq: { id: 'new-id', question: 'sample-question' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch faqs\n res.json({ faqs: [], total: 0 });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { question, answer, category } = req.body;\n // TODO: create FAQ\n res.status(201).json({ message: 'FAQ created', faq: { id: 'new-id', question } });\n};\n"},{"path":"src/model/Blog.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Blog = defineCollection('Blog', {\n title: { type: 'string', required: true },\n slug: { type: 'string', required: true, unique: true },\n content: { type: 'string', required: true },\n authorId: { type: 'string', required: true },\n category: { type: 'string', required: true, default: 'general' },\n tags: { type: 'array', of: 'string', default: [] },\n status: { type: 'string', required: true, default: 'draft' },\n publishedAt: { type: 'date' },\n});\n"},{"path":"src/model/Category.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Category = defineCollection('Category', {\n name: { type: 'string', required: true },\n slug: { type: 'string', required: true, unique: true },\n description: { type: 'string' },\n parentId: { type: 'string' },\n});\n"},{"path":"src/model/FAQ.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const FAQ = defineCollection('FAQ', {\n question: { type: 'string', required: true },\n answer: { type: 'string', required: true },\n category: { type: 'string', required: true, default: 'general' },\n order: { type: 'number', default: 0 },\n isPublished: { type: 'boolean', default: false },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-logs","files":[{"path":"src/api/admin/logs/activity.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Paginated activity log entries (admin only).',\n request: { query: { page: '1', limit: '50' } },\n response: { status: 200, body: { logs: [], total: 0, page: 1, limit: 50 } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { page = 1, limit = 50 } = req.query;\n // TODO: fetch activity logs with pagination\n res.json({ logs: [], total: 0, page: Number(page), limit: Number(limit) });\n};\n"},{"path":"src/api/admin/logs/audit.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Paginated audit log entries (admin only).',\n request: { query: { page: '1', limit: '50' } },\n response: { status: 200, body: { logs: [], total: 0, page: 1, limit: 50 } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { page = 1, limit = 50 } = req.query;\n // TODO: fetch audit logs with pagination\n res.json({ logs: [], total: 0, page: Number(page), limit: Number(limit) });\n};\n"},{"path":"src/api/admin/logs/security.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Paginated security log entries (admin only).',\n request: { query: { page: '1', limit: '50' } },\n response: { status: 200, body: { logs: [], total: 0, page: 1, limit: 50 } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { page = 1, limit = 50 } = req.query;\n // TODO: fetch security logs with pagination\n res.json({ logs: [], total: 0, page: Number(page), limit: Number(limit) });\n};\n"},{"path":"src/api/admin/notifications/broadcast.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Broadcast a notification to all users (admin only).',\n request: { body: { title: 'Announcement', message: 'Hello everyone!', type: 'info' } },\n response: { status: 200, body: { message: 'Broadcast sent', count: 0 } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const POST = async (req: Request, res: Response) => {\n const { title, message, type } = req.body;\n if (!title || !message) return res.status(400).json({ error: 'title and message are required' });\n // TODO: send notification to all users\n res.json({ message: 'Broadcast sent', count: 0 });\n};\n"},{"path":"src/api/admin/notifications/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all sent notifications (admin only).',\n response: { status: 200, body: { notifications: [], total: 0 } },\n },\n POST: {\n description: 'Send a notification to a specific user (admin only).',\n request: { body: { userId: 'usr_01HXZ', title: 'Welcome', message: 'Thanks for joining!', type: 'info' } },\n response: { status: 201, body: { message: 'Notification sent' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch sent notifications\n res.json({ notifications: [], total: 0 });\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { userId, title, message, type } = req.body;\n if (!userId || !title || !message) return res.status(400).json({ error: 'userId, title and message are required' });\n // TODO: create and send notification to user\n res.status(201).json({ message: 'Notification sent' });\n};\n"},{"path":"src/model/AuditLog.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const AuditLog = defineCollection('AuditLog', {\n adminId: { type: 'string', required: true },\n action: { type: 'string', required: true },\n entity: { type: 'string', required: true },\n entityId: { type: 'string', required: true },\n metadata: { type: 'object' },\n ip: { type: 'string', required: true },\n});\n"},{"path":"src/model/Notification.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Notification = defineCollection('Notification', {\n userId: { type: 'string', required: true },\n title: { type: 'string', required: true },\n message: { type: 'string', required: true },\n type: { type: 'string', required: true, default: 'info' },\n isRead: { type: 'boolean', default: false },\n link: { type: 'string' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-support","files":[{"path":"src/api/admin/tickets/[id].ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch a single support ticket by ID (admin only).',\n request: { params: { id: 'tk_01HXZ' } },\n response: { status: 200, body: { ticket: { id: 'tk_01HXZ' } } },\n },\n PUT: {\n description: 'Assign, reply to, or change the status of a support ticket (admin only).',\n request: { params: { id: 'tk_01HXZ' }, body: { reply: 'Looking into it.', status: 'in_progress', assignedTo: 'adm_01HXZ' } },\n response: { status: 200, body: { message: 'Ticket updated', ticket: { id: 'tk_01HXZ', status: 'in_progress', assignedTo: 'adm_01HXZ' } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { id } = req.params;\n // TODO: fetch ticket by id\n res.json({ ticket: { id } });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n const { reply, status, assignedTo } = req.body;\n // TODO: update ticket (assign, change status, add reply)\n res.json({ message: 'Ticket updated', ticket: { id, status, assignedTo } });\n};\n"},{"path":"src/api/admin/tickets/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'List all support tickets with filters (admin only).',\n request: { query: { status: 'open', priority: 'normal', page: '1', limit: '20' } },\n response: { status: 200, body: { tickets: [], total: 0, page: 1, limit: 20 } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n const { status, priority, page = 1, limit = 20 } = req.query;\n // TODO: fetch all tickets with filters\n res.json({ tickets: [], total: 0, page: Number(page), limit: Number(limit) });\n};\n"},{"path":"src/model/SupportTicket.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const SupportTicket = defineCollection('SupportTicket', {\n userId: { type: 'string', required: true },\n subject: { type: 'string', required: true },\n message: { type: 'string', required: true },\n status: { type: 'string', required: true, default: 'open' },\n priority: { type: 'string', required: true, default: 'normal' },\n assignedTo: { type: 'string' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-system","files":[{"path":"src/api/admin/settings/index.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Get system-wide settings (admin only).',\n response: { status: 200, body: { settings: {} } },\n },\n PUT: {\n description: 'Update system-wide settings (admin only).',\n request: { body: { maintenanceMode: false } },\n response: { status: 200, body: { message: 'Settings updated', settings: { maintenanceMode: false } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: fetch system settings from DB\n res.json({ settings: {} });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n // TODO: update system settings\n res.json({ message: 'Settings updated', settings: req.body });\n};\n"},{"path":"src/api/admin/system/cache.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n DELETE: {\n description: 'Flush the application cache (admin only).',\n response: { status: 200, body: { message: 'Cache cleared' } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const DELETE = async (_req: Request, res: Response) => {\n // TODO: flush Redis or in-memory cache\n res.json({ message: 'Cache cleared' });\n};\n"},{"path":"src/api/admin/system/health.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'System health check: DB, queue, cache status (admin only).',\n response: { status: 200, body: { status: 'ok', db: 'ok', queue: 'ok', uptime: 12345 } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n // TODO: check DB connection, queue, cache health\n res.json({ status: 'ok', db: 'ok', queue: 'ok', uptime: process.uptime() });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin-users","files":[{"path":"src/api/admin/users/[id].ts","content":"import { requireAuth, revokeAllSessions } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Fetch 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: Request, res: Response) => {\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: Request, res: Response) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.findByIdAndUpdate(id, { name, email, role, isActive }, { returnDocument: 'after' });\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: Request, res: Response) => {\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.findByIdAndDelete(id);\n await revokeAllSessions(id);\n res.json({ message: `User ${id} deleted` });\n};\n"},{"path":"src/api/admin/users/[id]/activate.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n 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: Request, res: Response) => {\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.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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.ts","content":"import { hashPassword, requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: '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: Request, res: Response) => {\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.countDocuments({})]);\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: Request, res: Response) => {\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":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"admin","files":[{"path":"src/api/admin/dashboard.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Admin dashboard stats. Requires admin role.',\n response: { status: 200, body: { stats: { totalUsers: 120, activeUsers: 98, verifiedUsers: 84 } } },\n },\n};\n\nexport const middlewares = [requireAuth('admin')];\n\nexport const GET = async (_req: Request, res: Response) => {\n const [totalUsers, activeUsers, verifiedUsers] = await Promise.all([\n User.countDocuments({}),\n User.countDocuments({ isActive: true }),\n User.countDocuments({ isVerified: true }),\n ]);\n res.json({ stats: { totalUsers, activeUsers, verifiedUsers } });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"auth","files":[{"path":"src/api/auth/login.ts","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { rateLimit } from 'express-file-cluster';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\n// 10 attempts per 15 minutes per address and account. Keyed on the email too, so behind a\n// proxy without TRUST_PROXY (every client then has the proxy's IP) it still limits one\n// account at a time, never everyone.\nexport const middlewares = [\n rateLimit({\n window: '15m',\n max: 10,\n key: (req) => `${req.ip}:${String(req.body?.email ?? '').toLowerCase()}`,\n }),\n];\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(\n res: Response,\n model: { findByIdAndUpdate: (id: string, data: Record<string, unknown>, options: { returnDocument: 'after' }) => Promise<unknown> },\n id: string,\n): Promise<string> {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.findByIdAndUpdate(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) }, { returnDocument: 'after' });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n return refreshToken;\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {\n return res.status(400).json({ error: 'email and password are required' });\n }\n\n const admin = await Admin.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.ts","content":"import { revokeSession } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n res.json({ user: (req as any).user });\n};\n"},{"path":"src/api/auth/register.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, email, password } = req.body;\n // Strings only: an object such as {\"$ne\": null} would be read as a filter operator and match any account.\n if (typeof name !== 'string' || typeof email !== 'string' || typeof password !== 'string' || !name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.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.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const Admin = defineCollection('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.ts","content":"import { defineCollection } from 'express-file-cluster';\n\nexport const User = defineCollection('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":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret(): Promise<string> {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name: string | undefined;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n const token = await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, await successRedirect(token, saved.appChallenge));\n};\n"},{"path":"src/api/auth/apple/index.ts","content":"import type { Request, Response } from 'express';\nimport { appChallengeFrom, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\n// Bearer apps add ?code_challenge=… (see appChallengeFrom in src/lib/oauth).\nexport const GET = async (req: Request, res: Response) => {\n const appChallenge = appChallengeFrom(req.query);\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce, ...(appChallenge ? { appChallenge } : {}) }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/api/auth/oauth/exchange.ts","content":"import type { Request, Response } from 'express';\nimport { exchangeCode } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Bearer apps: trade the one-time code from the sign-in redirect (plus the PKCE code_verifier) for a token.' },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n res.json({ token: await exchangeCode(req.body?.code, req.body?.code_verifier) });\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError, cache } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\nconst CODE_TTL_S = 60; // a bearer app has a minute to exchange its sign-in code\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n /** Bearer apps: the S256 challenge of a verifier only the app knows (app ↔ this server). */\n appChallenge?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<string | undefined> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.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.findByIdAndUpdate(account.id, { userId: user.id }, { returnDocument: 'after' });\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: Request['query']): string | undefined {\n const challenge = query.code_challenge;\n if (challenge === undefined) return undefined;\n if (typeof challenge !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {\n throw new HttpError(400, 'code_challenge must be the base64url SHA-256 of your code_verifier');\n }\n return challenge;\n}\n\n/**\n * Where the browser goes once signed in. With authStrategy 'bearer' the JWT never goes in the\n * URL (history, screenshots, logs): it gets a one-time code, valid for a minute, which the app\n * that started the sign-in trades for the token at POST /auth/oauth/exchange.\n */\nexport async function successRedirect(\n token?: string,\n appChallenge?: string,\n): Promise<string> {\n const to = process.env.OAUTH_SUCCESS_REDIRECT || '/';\n if (!token) return to;\n if (!appChallenge) {\n throw new HttpError(\n 400,\n 'Bearer sign-in needs a code_challenge — start at /auth/<provider>?code_challenge=…',\n );\n }\n const code = randomToken();\n await cache.set(`oauth:code:${code}`, { token, appChallenge }, { ttl: CODE_TTL_S });\n return `${to}#code=${code}`;\n}\n\n/**\n * The token for a one-time sign-in code, given the verifier behind the challenge the sign-in\n * started with. Once: a second use (or after a minute) gets 400.\n */\nexport async function exchangeCode(code: unknown, verifier: unknown): Promise<string> {\n if (typeof code !== 'string' || !code) throw new HttpError(400, 'code is required');\n if (typeof verifier !== 'string' || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {\n throw new HttpError(400, 'code_verifier is required (43-128 characters)');\n }\n const key = `oauth:code:${code}`;\n const saved = await cache.get<{ token: string; appChallenge: string }>(key);\n const expected = Buffer.from(saved?.appChallenge ?? '');\n const actual = Buffer.from(pkceChallenge(verifier));\n // A wrong verifier leaves the code alone, so it can't be used to burn someone's sign-in.\n if (!saved || expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {\n throw new HttpError(400, 'Invalid or expired sign-in code');\n }\n // del is atomic: of two requests racing with the same code, only one removes it.\n if ((await cache.del(key)) !== 1) throw new HttpError(400, 'Invalid or expired sign-in code');\n return saved.token;\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineCollection } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineCollection('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/"}]}
|