express-file-cluster 0.9.1 → 0.9.3
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 +8 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +12 -1
- package/dist/auth/index.d.ts +12 -1
- package/dist/auth/index.js +9 -3
- package/dist/{chunk-2J3HHQKP.cjs → chunk-ANUSWEAP.cjs} +55 -2
- package/dist/chunk-ANUSWEAP.cjs.map +1 -0
- package/dist/{chunk-RSZB7VAO.js → chunk-ATL4GYFU.js} +54 -1
- package/dist/chunk-ATL4GYFU.js.map +1 -0
- package/dist/cli/index.cjs +42 -88
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +80 -126
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +35 -0
- package/dist/docs/cli/add.md +2 -2
- package/dist/docs/cli/start.md +1 -1
- package/dist/docs/guides/authentication.md +30 -4
- package/dist/docs/guides/deployment.md +1 -1
- package/dist/docs/guides/environment-variables.md +1 -1
- package/dist/docs/index.md +1 -1
- package/dist/docs/skills/SKILL.md +2 -2
- package/dist/docs/skills/api-surface.md +8 -0
- package/dist/index.cjs +8 -8
- package/dist/index.js +1 -1
- package/dist/registry/index.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-client.json +1 -1
- package/dist/registry/js-mongo/forgot-password.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-client.json +1 -1
- package/dist/registry/js-pg-model/forgot-password.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-client.json +1 -1
- package/dist/registry/js-pg-table/forgot-password.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-client.json +1 -1
- package/dist/registry/ts-mongo/forgot-password.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-client.json +1 -1
- package/dist/registry/ts-pg-model/forgot-password.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-client.json +1 -1
- package/dist/registry/ts-pg-table/forgot-password.json +1 -1
- package/package.json +3 -3
- package/dist/chunk-2J3HHQKP.cjs.map +0 -1
- package/dist/chunk-RSZB7VAO.js.map +0 -1
|
@@ -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 { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport
|
|
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 +1 @@
|
|
|
1
|
-
{"name":"auth","files":[{"path":"src/api/auth/login.ts","content":"import { issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport
|
|
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<void> {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update(id, { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findOne({ email });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findOne({ email });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.ts","content":"import { revokeSession } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n res.json({ user: (req as any).user });\n};\n"},{"path":"src/api/auth/register.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findOne({ email });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ name, email, password: hashed, verifyToken });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.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
|
|
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 +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
|
|
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 +1 @@
|
|
|
1
|
-
{"name":"email-client","files":[{"path":"src/tasks/SendEmail.ts","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\ninterface SendEmailPayload {\n to: string;\n subject: string;\n body: string;\n}\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask<SendEmailPayload>(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^
|
|
1
|
+
{"name":"email-client","files":[{"path":"src/tasks/SendEmail.ts","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\ninterface SendEmailPayload {\n to: string;\n subject: string;\n body: string;\n}\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask<SendEmailPayload>(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^10.2.1"},"devDependencies":{"@types/nodemailer":"^8.0.2"},"env":[{"key":"APP_URL","value":"http://localhost:3000","example":"http://localhost:3000"},{"key":"SMTP_HOST","value":"smtp.gmail.com","example":"smtp.gmail.com"},{"key":"SMTP_PORT","value":"465","example":"465"},{"key":"SMTP_USER","value":"","example":"your@email.com"},{"key":"SMTP_PASS","value":" # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords","example":"your_16_char_app_password # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords"},{"key":"SMTP_FROM","value":"noreply@example.com","example":"noreply@yourapp.com"}]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.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
|
|
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 +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.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update({ where: { id }, data: { name, email, role, isActive } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n 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.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete({ where: { 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 { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport
|
|
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.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n const { password: _, ...safe } = user;\n res.json({ user: safe });\n};\n\nexport const PUT = async (req: Request, res: Response) => {\n const { id } = req.params;\n const { name, email, role, isActive } = req.body;\n const updated = await User.update({ where: { id }, data: { name, email, role, isActive } });\n if (!updated) return res.status(404).json({ error: 'User not found' });\n 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.findUnique({ where: { id } });\n if (!user) return res.status(404).json({ error: 'User not found' });\n await User.delete({ where: { 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.findMany(), 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.findFirst({ where: { email } });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const user = await User.create({ data: { name, email, password: hashed, role: role ?? 'user' } });\n const { password: _, ...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 } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport
|
|
1
|
+
{"name":"auth","files":[{"path":"src/api/auth/login.ts","content":"import { issueToken, verifyPassword } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Authenticate a user or admin and issue a JWT.',\n request: { body: { email: 'user@example.com', password: 'user' } },\n response: { status: 200, body: { message: 'Logged in as user' } },\n },\n};\n\nconst REFRESH_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days\n\nasync function issueRefreshToken(\n res: Response,\n model: { update: (args: { where: { id: string }; data: Record<string, unknown> }) => Promise<unknown> },\n id: string,\n): Promise<void> {\n const refreshToken = crypto.randomBytes(40).toString('hex');\n await model.update({ where: { id }, data: { refreshToken, refreshTokenExpiry: new Date(Date.now() + REFRESH_TOKEN_TTL_MS) } });\n res.cookie('efc_refresh_token', refreshToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'strict',\n maxAge: REFRESH_TOKEN_TTL_MS,\n });\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { email, password } = req.body;\n if (!email || !password) return res.status(400).json({ error: 'email and password are required' });\n\n const admin = await Admin.findFirst({ where: { email } });\n if (admin) {\n const match = await verifyPassword(password, admin.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!admin.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: admin.id, role: admin.role, email: admin.email });\n await issueRefreshToken(res, Admin, admin.id);\n return res.json({ message: 'Logged in as admin' });\n }\n\n const user = await User.findFirst({ where: { email } });\n if (!user) return res.status(401).json({ error: 'Invalid credentials' });\n const match = await verifyPassword(password, user.password);\n if (!match) return res.status(401).json({ error: 'Invalid credentials' });\n if (!user.isActive) return res.status(403).json({ error: 'Account suspended' });\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n await issueRefreshToken(res, User, user.id);\n res.json({ message: 'Logged in' });\n};\n"},{"path":"src/api/auth/logout.ts","content":"import { revokeSession } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Revoke the current session and clear the auth cookie.',\n response: { status: 200, body: { message: 'Logged out successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n // Rejects this token from now on (not just the cookie) — see `cache` in efc.config.\n await revokeSession(req, res);\n res.clearCookie('efc_refresh_token');\n res.json({ message: 'Logged out successfully' });\n};\n"},{"path":"src/api/auth/me.ts","content":"import { requireAuth } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: {\n description: 'Return the currently authenticated user.',\n response: { status: 200, body: { user: { id: '1', role: 'user', email: 'user@example.com' } } },\n },\n};\n\nexport const middlewares = [requireAuth('user', 'admin')];\n\nexport const GET = async (req: Request, res: Response) => {\n res.json({ user: (req as any).user });\n};\n"},{"path":"src/api/auth/register.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword } from 'express-file-cluster/auth';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Register a new user account.',\n request: { body: { name: 'Jane Doe', email: 'jane@example.com', password: 'secret' } },\n response: { status: 201, body: { message: 'Account created successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { name, email, password } = req.body;\n if (!name || !email || !password) {\n return res.status(400).json({ error: 'name, email and password are required' });\n }\n const existing = await User.findFirst({ where: { email } });\n if (existing) return res.status(409).json({ error: 'Email already in use' });\n const hashed = await hashPassword(password);\n const verifyToken = crypto.randomBytes(32).toString('hex');\n const user = await User.create({ data: { name, email, password: hashed, verifyToken } });\n\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Verify your email address',\n body: 'Welcome, ' + name + '! Verify your email: ' + appUrl + '/auth/verify-email?token=' + verifyToken,\n });\n\n const { password: _, verifyToken: __, ...safe } = user;\n res.status(201).json({ message: 'Account created successfully', user: safe });\n};\n"},{"path":"src/model/Admin.ts","content":"import { defineTable } from 'express-file-cluster';\n\nexport const Admin = defineTable('Admin', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'admin' },\n permissions: { type: 'array', of: 'string', default: [] },\n isActive: { type: 'boolean', default: true },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"},{"path":"src/model/User.ts","content":"import { defineTable } from 'express-file-cluster';\n\nexport const User = defineTable('User', {\n name: { type: 'string', required: true },\n email: { type: 'string', required: true, unique: true },\n password: { type: 'string', required: true },\n role: { type: 'string', required: true, default: 'user' },\n avatar: { type: 'string' },\n isVerified: { type: 'boolean', default: false },\n isActive: { type: 'boolean', default: true },\n verifyToken: { type: 'string' },\n resetToken: { type: 'string' },\n resetTokenExpiry: { type: 'date' },\n refreshToken: { type: 'string' },\n refreshTokenExpiry: { type: 'date' },\n});\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
|
@@ -1 +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
|
|
1
|
+
{"name":"auth@apple","files":[{"path":"src/api/auth/apple/callback.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { SignJWT, createRemoteJWKSet, importPKCS8, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: { description: 'Apple posts here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst APPLE_KEYS = createRemoteJWKSet(new URL('https://appleid.apple.com/auth/keys'));\n\n// Apple's client secret is a short-lived ES256 JWT signed with your Sign in with Apple key\n// (APPLE_PRIVATE_KEY: the .p8 file's contents, newlines written as \\n).\nasync function clientSecret(): Promise<string> {\n const key = await importPKCS8((process.env.APPLE_PRIVATE_KEY ?? '').replace(/\\\\n/g, '\\n'), 'ES256');\n return new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: process.env.APPLE_KEY_ID ?? '' })\n .setIssuer(process.env.APPLE_TEAM_ID ?? '')\n .setSubject(process.env.APPLE_CLIENT_ID ?? '')\n .setAudience('https://appleid.apple.com')\n .setIssuedAt()\n .setExpirationTime('5m')\n .sign(key);\n}\n\nexport const POST = async (req: Request, res: Response) => {\n const { code, state, user, error } = req.body ?? {};\n if (error) throw new HttpError(400, `Apple sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'apple', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://appleid.apple.com/auth/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n client_secret: await clientSecret(),\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Apple rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, APPLE_KEYS, {\n issuer: 'https://appleid.apple.com',\n audience: process.env.APPLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n // Apple sends the user's name once, on their first sign-in, as a JSON form field.\n let name: string | undefined;\n try {\n const n = typeof user === 'string' ? JSON.parse(user).name : undefined;\n name = [n?.firstName, n?.lastName].filter(Boolean).join(' ') || undefined;\n } catch {\n name = undefined;\n }\n\n await signInWithOAuth(res, {\n provider: 'apple',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true || payload.email_verified === 'true',\n name,\n });\n res.redirect(303, successRedirect());\n};\n"},{"path":"src/api/auth/apple/index.ts","content":"import type { Request, Response } from 'express';\nimport { randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Apple\": redirects to Apple.' },\n};\n\n// Redirects to Apple; Apple POSTs the result to the callback route (APPLE_REDIRECT_URI —\n// register it on the Services ID; Apple only accepts https URLs on a verified domain).\nexport const GET = async (_req: Request, res: Response) => {\n const state = randomToken();\n const nonce = randomToken();\n rememberState(res, 'apple', { state, nonce }, true);\n const params = new URLSearchParams({\n client_id: process.env.APPLE_CLIENT_ID ?? '',\n redirect_uri: process.env.APPLE_REDIRECT_URI ?? '',\n response_type: 'code',\n response_mode: 'form_post',\n scope: 'name email',\n state,\n nonce,\n });\n res.redirect(`https://appleid.apple.com/auth/authorize?${params}`);\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<void> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: user.id,\n } });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect(): string {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"APPLE_CLIENT_ID","value":"","example":"com.yourapp.signin"},{"key":"APPLE_TEAM_ID","value":"","example":"ABCDE12345"},{"key":"APPLE_KEY_ID","value":"","example":"FGHIJ67890"},{"key":"APPLE_PRIVATE_KEY","value":"","example":"-----BEGIN PRIVATE KEY-----\\n...\\n-----END PRIVATE KEY-----"},{"key":"APPLE_REDIRECT_URI","value":"https://api.yourapp.com/v1/api/auth/apple/callback","example":"https://api.yourapp.com/v1/api/auth/apple/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
|
|
@@ -1 +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
|
|
1
|
+
{"name":"auth@google","files":[{"path":"src/api/auth/google/callback.ts","content":"import { HttpError } from 'express-file-cluster';\nimport { createRemoteJWKSet, jwtVerify } from 'jose';\nimport type { Request, Response } from 'express';\nimport { signInWithOAuth, successRedirect, takeState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Google redirects here after sign-in; signs the user in and redirects to OAUTH_SUCCESS_REDIRECT.' },\n};\n\nconst GOOGLE_KEYS = createRemoteJWKSet(new URL('https://www.googleapis.com/oauth2/v3/certs'));\n\nexport const GET = async (req: Request, res: Response) => {\n const { code, state, error } = req.query;\n if (error) throw new HttpError(400, `Google sign-in failed: ${String(error)}`);\n const saved = takeState(req, res, 'google', state);\n if (!saved || typeof code !== 'string') {\n throw new HttpError(400, 'Sign-in attempt expired or invalid — start again');\n }\n\n const tokens = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n code,\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n grant_type: 'authorization_code',\n code_verifier: saved.verifier ?? '',\n }),\n });\n if (!tokens.ok) throw new HttpError(502, `Google rejected the sign-in (${tokens.status})`);\n const { id_token } = (await tokens.json()) as { id_token: string };\n\n const { payload } = await jwtVerify(id_token, GOOGLE_KEYS, {\n issuer: ['https://accounts.google.com', 'accounts.google.com'],\n audience: process.env.GOOGLE_CLIENT_ID ?? '',\n });\n if (payload.nonce !== saved.nonce) throw new HttpError(400, 'Invalid sign-in response');\n\n await signInWithOAuth(res, {\n provider: 'google',\n providerId: String(payload.sub),\n email: payload.email as string | undefined,\n emailVerified: payload.email_verified === true,\n name: payload.name as string | undefined,\n });\n res.redirect(successRedirect());\n};\n"},{"path":"src/api/auth/google/index.ts","content":"import type { Request, Response } from 'express';\nimport { pkceChallenge, randomToken, rememberState } from '../../../lib/oauth.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n GET: { description: 'Start \"Sign in with Google\": redirects to Google.' },\n};\n\n// Redirects to Google's consent screen; Google sends the browser back to the callback route\n// (GOOGLE_REDIRECT_URI — register that exact URL in the Google Cloud console).\nexport const GET = async (_req: Request, res: Response) => {\n const state = randomToken();\n const nonce = randomToken();\n const verifier = randomToken();\n rememberState(res, 'google', { state, nonce, verifier });\n const params = new URLSearchParams({\n client_id: process.env.GOOGLE_CLIENT_ID ?? '',\n redirect_uri: process.env.GOOGLE_REDIRECT_URI ?? '',\n response_type: 'code',\n scope: 'openid email profile',\n state,\n nonce,\n code_challenge: pkceChallenge(verifier),\n code_challenge_method: 'S256',\n prompt: 'select_account',\n });\n res.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params}`);\n};\n"},{"path":"src/lib/oauth.ts","content":"import crypto from 'node:crypto';\nimport { HttpError } from 'express-file-cluster';\nimport { hashPassword, issueToken } from 'express-file-cluster/auth';\nimport type { Request, Response } from 'express';\nimport { User } from '../model/User.js';\nimport { OAuthAccount } from '../model/OAuthAccount.js';\n\n// Shared by the OAuth sign-in routes (src/api/auth/<provider>/).\n\nconst STATE_TTL_MS = 10 * 60 * 1000; // a sign-in attempt has 10 minutes to come back\n\nexport interface OAuthState {\n state: string;\n nonce: string;\n verifier?: string;\n}\n\nexport interface OAuthProfile {\n provider: 'google' | 'apple';\n providerId: string;\n email?: string;\n emailVerified: boolean;\n name?: string;\n}\n\n/** A random URL-safe string (state, nonce, PKCE verifier). */\nexport function randomToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/** The PKCE S256 challenge for a verifier. */\nexport function pkceChallenge(verifier: string): string {\n return crypto.createHash('sha256').update(verifier).digest('base64url');\n}\n\n/**\n * Remembers a sign-in attempt in a short-lived cookie until the provider redirects back.\n * `crossSite`: the provider POSTs the callback from its own site (Apple), so the cookie must\n * be SameSite=None — which browsers only accept with Secure (https, or localhost).\n */\nexport function rememberState(\n res: Response,\n provider: string,\n data: OAuthState,\n crossSite = false,\n): void {\n res.cookie(`efc_oauth_${provider}`, JSON.stringify(data), {\n httpOnly: true,\n secure: crossSite || process.env.NODE_ENV === 'production',\n sameSite: crossSite ? 'none' : 'lax',\n maxAge: STATE_TTL_MS,\n path: '/',\n });\n}\n\n/** The remembered attempt (cleared) — or undefined if `state` doesn't match it. */\nexport function takeState(\n req: Request,\n res: Response,\n provider: string,\n state: unknown,\n): OAuthState | undefined {\n const name = `efc_oauth_${provider}`;\n const raw = (req as Request & { cookies?: Record<string, string> }).cookies?.[name];\n res.clearCookie(name, { path: '/' });\n if (!raw || typeof state !== 'string') return undefined;\n try {\n const saved = JSON.parse(raw) as OAuthState;\n const a = Buffer.from(String(saved.state));\n const b = Buffer.from(state);\n return a.length === b.length && crypto.timingSafeEqual(a, b) ? saved : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Signs in the user behind a provider identity: the account already linked to it, else the\n * user with the same (provider-verified) email, else a new user. New users get a random\n * password — they can set a real one with the forgot-password flow.\n */\nexport async function signInWithOAuth(res: Response, profile: OAuthProfile): Promise<void> {\n const key = `${profile.provider}:${profile.providerId}`;\n const account = await OAuthAccount.findFirst({ where: { key } });\n let user = account ? await User.findUnique({ where: { id: account.user } }) : null;\n if (!user) {\n if (!profile.email || !profile.emailVerified) {\n throw new HttpError(400, `${profile.provider} did not return a verified email address`);\n }\n const email = profile.email;\n user =\n (await User.findFirst({ where: { email } })) ??\n (await User.create({ data: {\n name: profile.name || email.split('@')[0],\n email,\n password: await hashPassword(randomToken()),\n isVerified: true,\n } }));\n if (account) await OAuthAccount.update({ where: { id: account.id }, data: { user: user.id } });\n else {\n await OAuthAccount.create({ data: {\n key,\n provider: profile.provider,\n providerId: profile.providerId,\n email,\n user: user.id,\n } });\n }\n }\n if (!user.isActive) throw new HttpError(403, 'Account suspended');\n await issueToken(res, { id: user.id, role: user.role, email: user.email });\n}\n\n/** Where the browser goes once signed in. */\nexport function successRedirect(): string {\n return process.env.OAUTH_SUCCESS_REDIRECT || '/';\n}\n"},{"path":"src/model/OAuthAccount.ts","content":"import { defineTable } from 'express-file-cluster';\n\n// One row per provider identity (\"google:<sub>\"), linked to the User it signs in as.\nexport const OAuthAccount = defineTable('OAuthAccount', {\n key: { type: 'string', required: true, unique: true },\n provider: { type: 'string', required: true, enum: ['google', 'apple'] },\n providerId: { type: 'string', required: true },\n email: { type: 'string' },\n user: { type: 'uuid', ref: 'User', required: true, onDelete: 'cascade' },\n});\n"}],"dependencies":{"jose":"^6.2.3"},"devDependencies":{},"env":[{"key":"GOOGLE_CLIENT_ID","value":"","example":"your-client-id.apps.googleusercontent.com"},{"key":"GOOGLE_CLIENT_SECRET","value":"","example":"your-client-secret"},{"key":"GOOGLE_REDIRECT_URI","value":"http://localhost:3000/v1/api/auth/google/callback","example":"https://api.yourapp.com/v1/api/auth/google/callback"},{"key":"OAUTH_SUCCESS_REDIRECT","value":"http://localhost:3000/","example":"https://yourapp.com/"}]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"email-client","files":[{"path":"src/tasks/SendEmail.ts","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\ninterface SendEmailPayload {\n to: string;\n subject: string;\n body: string;\n}\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask<SendEmailPayload>(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^
|
|
1
|
+
{"name":"email-client","files":[{"path":"src/tasks/SendEmail.ts","content":"import { defineTask } from 'express-file-cluster/tasks';\nimport nodemailer from 'nodemailer';\n\ninterface SendEmailPayload {\n to: string;\n subject: string;\n body: string;\n}\n\nconst transporter = nodemailer.createTransport({\n host: process.env.SMTP_HOST,\n port: Number(process.env.SMTP_PORT ?? 587),\n secure: Number(process.env.SMTP_PORT) === 465,\n auth: {\n user: process.env.SMTP_USER,\n pass: process.env.SMTP_PASS,\n },\n});\n\nexport default defineTask<SendEmailPayload>(async (payload) => {\n await transporter.sendMail({\n from: process.env.SMTP_FROM ?? process.env.SMTP_USER,\n to: payload.to,\n subject: payload.subject,\n html: payload.body,\n });\n});\n"}],"dependencies":{"nodemailer":"^10.2.1"},"devDependencies":{"@types/nodemailer":"^8.0.2"},"env":[{"key":"APP_URL","value":"http://localhost:3000","example":"http://localhost:3000"},{"key":"SMTP_HOST","value":"smtp.gmail.com","example":"smtp.gmail.com"},{"key":"SMTP_PORT","value":"465","example":"465"},{"key":"SMTP_USER","value":"","example":"your@email.com"},{"key":"SMTP_PASS","value":" # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords","example":"your_16_char_app_password # Gmail App Password (16 chars) — NOT your regular Gmail password. Generate at: Google Account > Security > 2-Step Verification > App passwords"},{"key":"SMTP_FROM","value":"noreply@example.com","example":"noreply@yourapp.com"}]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n const admin = user ? null : await Admin.findFirst({ where: { email } });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update({ where: { id: user.id }, data: { resetToken, resetTokenExpiry } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { resetToken, resetTokenExpiry } });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.ts","content":"import type { Request, Response } from 'express';\nimport
|
|
1
|
+
{"name":"forgot-password","files":[{"path":"src/api/auth/forgot-password.ts","content":"import type { Request, Response } from 'express';\nimport crypto from 'node:crypto';\nimport { enqueue } from 'express-file-cluster/tasks';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Send a password reset email to the given address.',\n request: { body: { email: 'user@example.com' } },\n response: { status: 200, body: { message: 'Reset email sent' } },\n },\n};\n\nconst RESET_TOKEN_TTL_MS = 1000 * 60 * 60; // 1 hour\n\nexport const POST = async (req: Request, res: Response) => {\n const { email } = req.body;\n if (!email) return res.status(400).json({ error: 'email is required' });\n\n const user = await User.findFirst({ where: { email } });\n const admin = user ? null : await Admin.findFirst({ where: { email } });\n\n // Always respond the same way whether or not the account exists, so this\n // endpoint can't be used to enumerate registered emails.\n if (user || admin) {\n const resetToken = crypto.randomBytes(32).toString('hex');\n const resetTokenExpiry = new Date(Date.now() + RESET_TOKEN_TTL_MS);\n if (user) await User.update({ where: { id: user.id }, data: { resetToken, resetTokenExpiry } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { resetToken, resetTokenExpiry } });\n var appUrl = process.env.APP_URL || 'http://localhost:3000';\n await enqueue('SendEmail', {\n to: email,\n subject: 'Reset your password',\n body: 'Reset your password: ' + appUrl + '/auth/reset-password?token=' + resetToken,\n });\n }\n\n res.json({ message: 'Reset email sent' });\n};\n"},{"path":"src/api/auth/reset-password.ts","content":"import type { Request, Response } from 'express';\nimport { hashPassword, revokeAllSessions } from 'express-file-cluster/auth';\nimport { User } from '../../model/User.js';\nimport { Admin } from '../../model/Admin.js';\nimport type { RouteMeta } from 'express-file-cluster';\n\nexport const meta: RouteMeta = {\n POST: {\n description: 'Reset password using a valid reset token.',\n request: { body: { token: 'reset-token', password: 'newpassword' } },\n response: { status: 200, body: { message: 'Password reset successfully' } },\n },\n};\n\nexport const POST = async (req: Request, res: Response) => {\n const { token, password } = req.body;\n if (!token || !password) return res.status(400).json({ error: 'token and password are required' });\n\n const user = await User.findFirst({ where: { resetToken: token } });\n const admin = user ? null : await Admin.findFirst({ where: { resetToken: token } });\n const account = user || admin;\n\n if (!account || !account.resetTokenExpiry || new Date(account.resetTokenExpiry) < new Date()) {\n return res.status(400).json({ error: 'Invalid or expired reset token' });\n }\n\n const hashed = await hashPassword(password);\n if (user) await User.update({ where: { id: user.id }, data: { password: hashed, resetToken: '' } });\n else if (admin) await Admin.update({ where: { id: admin.id }, data: { password: hashed, resetToken: '' } });\n // Tokens issued with the old password stop working everywhere.\n await revokeAllSessions(account.id);\n\n res.json({ message: 'Password reset successfully' });\n};\n"}],"dependencies":{},"devDependencies":{},"env":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-file-cluster",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.3",
|
|
4
4
|
"description": "Enterprise-grade, zero-boilerplate backend framework with file-based routing and multi-core clustering",
|
|
5
5
|
"homepage": "https://efc.prashantadhikari7.com.np/",
|
|
6
6
|
"repository": {
|
|
@@ -69,8 +69,8 @@
|
|
|
69
69
|
"supertest": "^7.2.2",
|
|
70
70
|
"tsup": "^8.2.0",
|
|
71
71
|
"typescript": "^5.5.0",
|
|
72
|
-
"vitest": "^4.1.
|
|
73
|
-
"zod": "^4.6.
|
|
72
|
+
"vitest": "^4.1.12",
|
|
73
|
+
"zod": "^4.6.7"
|
|
74
74
|
},
|
|
75
75
|
"peerDependencies": {
|
|
76
76
|
"bullmq": ">=5.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-2J3HHQKP.cjs","../src/auth/index.ts","../src/cache/index.ts","../src/cache/ipc.ts"],"names":["pending","prefix","cluster","randomUUID"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACXA,gCAA2B;AAE3B,4BAAoD;ADYpD;AACA;AEfA,oFAAoB;AFiBpB;AACA;AGlBA;AACA;AAUA,IAAM,IAAA,EAAM,YAAA;AACZ,IAAM,WAAA,EAAa,GAAA;AAiBnB,IAAM,SAAA,EAAW,CAAC,GAAA,EAAA,GAChB,IAAA,IAAQ,KAAA,GAAQ,OAAO,IAAA,IAAQ,SAAA,GAAa,GAAA,CAAgC,GAAG,EAAA,IAAM,IAAA;AAGhF,SAAS,iBAAA,CAAkB,UAAA,EAA0B;AAC1D,EAAA,MAAM,MAAA,EAAQ,aAAA,CAAc,UAAU,CAAA;AACtC,EAAA,iBAAA,CAAQ,EAAA,CAAG,SAAA,EAAW,CAAC,MAAA,EAAgB,GAAA,EAAA,GAAiB;AACtD,IAAA,GAAA,CAAI,CAAC,QAAA,CAAS,GAAG,CAAA,EAAG,MAAA;AACpB,IAAA,MAAM,IAAA,EAAM,GAAA;AACZ,IAAA,MAAM,IAAA,EAAM,MAAA,CAAA,EAAA,GAA8B;AACxC,MAAA,OAAA,CAAQ,GAAA,CAAI,EAAA,EAAI;AAAA,QACd,KAAK,MAAA;AACH,UAAA,OAAO,MAAA;AAAA,QACT,KAAK,KAAA;AACH,UAAA,OAAO,KAAA,CAAM,GAAA,CAAI,GAAA,CAAI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A;AACsC,EAAA;AACH,EAAA;AACvD;AAMgF;AACvD,EAAA;AACiC,EAAA;AAC1D;AAOiB;AACX,EAAA;AACyB,IAAA;AAEf,IAAA;AACoC,MAAA;AAC9C,MAAA;AACF,IAAA;AAEkC,IAAA;AAET,IAAA;AACT,MAAA;AACV,MAAA;AAC+B,QAAA;AACrB,MAAA;AAC+B,QAAA;AACI,QAAA;AACd,UAAA;AACnB,UAAA;AACJ,YAAA;AAC+B,YAAA;AACvC,UAAA;AACF,QAAA;AAGY,QAAA;AACoB,UAAA;AAC9B,UAAA;AACF,QAAA;AACF,MAAA;AACa,MAAA;AACmC,QAAA;AAC9C,QAAA;AACF,MAAA;AACF,IAAA;AAEsB,IAAA;AACoC,MAAA;AACJ,MAAA;AACP,QAAA;AAC3C,QAAA;AACF,MAAA;AACF,IAAA;AAE+C,IAAA;AACE,IAAA;AAC5C,IAAA;AACC,EAAA;AACwC,IAAA;AAChD,EAAA;AACF;AAYiE;AACX,EAAA;AACpC,IAAA;AAC8C,IAAA;AACnB,MAAA;AACzC,IAAA;AACF,EAAA;AACyB,EAAA;AACW,EAAA;AACtC;ADsM0D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/express-file-cluster/express-file-cluster/packages/core/dist/chunk-2J3HHQKP.cjs","sourcesContent":[null,"import { randomUUID } from 'node:crypto';\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { SignJWT, jwtVerify, type JWTPayload } from 'jose';\nimport type { AuthStrategy } from '../types.js';\nimport { setCurrentUser } from '../context.js';\nimport { isCacheConfigured, rawGet, rawSet, revocationFailureMode } from '../cache/index.js';\nimport { getLogger } from '../logger.js';\n\ninterface AuthConfig {\n secret: string;\n strategy: AuthStrategy;\n expiresIn: string;\n cookieDomain?: string | undefined;\n}\n\nlet _config: AuthConfig | null = null;\n\nexport function configureAuth(config: AuthConfig): void {\n _config = config;\n}\n\nfunction getConfig(): AuthConfig {\n if (!_config) throw new Error('[EFC] Auth not configured — pass jwtSecret to ignite()');\n return _config;\n}\n\n// Every token carries a unique `jti` (so one session can be revoked) and its issue\n// time in milliseconds, `efc_iat` (so \"revoke all sessions issued before now\" doesn't\n// also catch a token minted in the same second as the revocation).\nasync function sign(payload: Record<string, unknown>): Promise<string> {\n const { secret, expiresIn } = getConfig();\n return new SignJWT({ ...payload, efc_iat: Date.now() })\n .setProtectedHeader({ alg: 'HS256' })\n .setJti(randomUUID())\n .setIssuedAt()\n .setExpirationTime(expiresIn)\n .sign(new TextEncoder().encode(secret));\n}\n\nexport async function issueToken(res: Response, payload: Record<string, unknown>): Promise<void> {\n const { cookieDomain } = getConfig();\n const token = await sign(payload);\n\n res.cookie('efc_token', token, {\n httpOnly: true,\n secure: process.env['NODE_ENV'] === 'production',\n sameSite: 'strict',\n ...(cookieDomain !== undefined && { domain: cookieDomain }),\n });\n}\n\nexport function revokeToken(res: Response): void {\n res.clearCookie('efc_token');\n}\n\nexport async function signToken(payload: Record<string, unknown>): Promise<string> {\n return sign(payload);\n}\n\nfunction tokenFrom(req: Request): string | undefined {\n if (getConfig().strategy === 'http-only') {\n return (req as typeof req & { cookies?: Record<string, string> }).cookies?.['efc_token'];\n }\n const auth = req.headers['authorization'];\n return typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice(7) : undefined;\n}\n\nasync function verify(token: string): Promise<JWTPayload> {\n const { payload } = await jwtVerify(token, new TextEncoder().encode(getConfig().secret));\n return payload;\n}\n\nconst userIdOf = (payload: JWTPayload): string | undefined => {\n const id = payload.sub ?? (payload as Record<string, unknown>)['id'];\n return id === undefined || id === null ? undefined : String(id);\n};\n\n// ── Session revocation (needs `cache` in ignite()) ───────────────────────────\n// Stateless JWTs can't be \"un-issued\", so revocation is a denylist in the cache:\n// one key per revoked token (`sess:jti:<jti>`, kept until that token would expire)\n// and one per user for \"everything issued before T\" (`sess:user:<id>`).\n\n/** Lifetime of a token signed now, in seconds — `jwtExpiresIn` like '15m', '7d'. */\nfunction tokenLifetimeSeconds(): number {\n const m =\n /^(\\d+(?:\\.\\d+)?)\\s*(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?|d|days?|w|weeks?|y|yrs?|years?)?$/i.exec(\n getConfig().expiresIn.trim(),\n );\n if (!m) return 30 * 86_400;\n const n = Number(m[1]);\n const unit = (m[2] ?? 's')[0]!.toLowerCase();\n const factor = { s: 1, m: 60, h: 3600, d: 86_400, w: 604_800, y: 31_557_600 }[unit] ?? 1;\n return Math.ceil(n * factor);\n}\n\nlet lastRevocationError = 0;\n\nasync function isRevoked(payload: JWTPayload): Promise<boolean> {\n if (payload.jti && (await rawGet(`sess:jti:${payload.jti}`)) !== null) return true;\n const userId = userIdOf(payload);\n if (userId === undefined) return false;\n const cutoff = await rawGet(`sess:user:${userId}`);\n if (cutoff === null) return false;\n const issuedMs =\n typeof (payload as Record<string, unknown>)['efc_iat'] === 'number'\n ? ((payload as Record<string, unknown>)['efc_iat'] as number)\n : (payload.iat ?? 0) * 1000; // tokens minted before efc_iat existed\n return issuedMs < Number(cutoff);\n}\n\nfunction requireRevocationStore(): void {\n if (!isCacheConfigured()) {\n throw new Error(\n '[EFC] Session revocation needs a cache — pass cache: { backend: \"redis\" } to ignite()',\n );\n }\n}\n\n/**\n * Revokes the token the current request was authenticated with: `requireAuth` rejects\n * it from now until it would have expired anyway. Pass `res` to also clear the cookie\n * (http-only strategy). Throws if the cache is unreachable, so a failed logout is visible.\n */\nexport async function revokeSession(req: Request, res?: Response): Promise<void> {\n requireRevocationStore();\n const token = tokenFrom(req);\n if (res && getConfig().strategy === 'http-only') res.clearCookie('efc_token');\n if (!token) return;\n let payload: JWTPayload;\n try {\n payload = await verify(token);\n } catch {\n return; // already invalid or expired — nothing to revoke\n }\n if (!payload.jti) return;\n const ttl = payload.exp ? payload.exp - Math.floor(Date.now() / 1000) : tokenLifetimeSeconds();\n if (ttl > 0) await rawSet(`sess:jti:${payload.jti}`, '1', ttl);\n}\n\n/**\n * Revokes every token issued to `userId` (the JWT's `sub` or `id` claim) before now —\n * \"log out of all devices\", or after a password change. Tokens issued afterwards work.\n */\nexport async function revokeAllSessions(userId: string | number): Promise<void> {\n requireRevocationStore();\n await rawSet(`sess:user:${String(userId)}`, String(Date.now()), tokenLifetimeSeconds());\n}\n\nasync function authenticate(\n req: Request,\n res: Response,\n next: NextFunction,\n roles: string[],\n): Promise<void> {\n try {\n const token = tokenFrom(req);\n\n if (!token) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n\n const payload = await verify(token);\n\n if (isCacheConfigured()) {\n let revoked = false;\n try {\n revoked = await isRevoked(payload);\n } catch (err) {\n const reject = revocationFailureMode() === 'reject';\n if (Date.now() - lastRevocationError > 30_000) {\n lastRevocationError = Date.now();\n getLogger().error(\n { err },\n `Session revocation check failed — ${reject ? 'rejecting with 503' : 'allowing'} authenticated requests`,\n );\n }\n // 503, not 401: the session isn't invalid, the check is unavailable — clients\n // shouldn't discard the token and force a re-login over a cache blip.\n if (reject) {\n res.status(503).json({ error: 'Service Unavailable', statusCode: 503 });\n return;\n }\n }\n if (revoked) {\n res.status(401).json({ error: 'Unauthorized' });\n return;\n }\n }\n\n if (roles.length > 0) {\n const role = (payload as Record<string, unknown>)['role'];\n if (typeof role !== 'string' || !roles.includes(role)) {\n res.status(403).json({ error: 'Forbidden' });\n return;\n }\n }\n\n (req as typeof req & { user: unknown }).user = payload;\n setCurrentUser(payload as Record<string, unknown>);\n next();\n } catch {\n res.status(401).json({ error: 'Unauthorized' });\n }\n}\n\n/**\n * Used bare (`middlewares = [requireAuth]`) it just verifies the JWT.\n * Called with role names (`middlewares = [requireAuth('admin')]`) it\n * returns a middleware that also enforces `payload.role` is one of them.\n */\nexport interface RequireAuth {\n (req: Request, res: Response, next: NextFunction): void;\n (...roles: string[]): RequestHandler;\n}\n\nexport const requireAuth: RequireAuth = ((...args: unknown[]) => {\n if (args.length > 0 && typeof args[0] === 'string') {\n const roles = args as string[];\n return (req: Request, res: Response, next: NextFunction) => {\n void authenticate(req, res, next, roles);\n };\n }\n const [req, res, next] = args as [Request, Response, NextFunction];\n void authenticate(req, res, next, []);\n}) as RequireAuth;\n\n// Reads the JWT payload requireAuth attached for the in-flight request, from\n// anywhere — not just where `req` is in scope. Returns undefined outside a\n// request, or on a request that never ran through requireAuth.\nexport { getCurrentUser } from '../context.js';\n","import cluster from 'node:cluster';\nimport type { Redis as RedisClient, RedisOptions } from 'ioredis';\nimport type { CacheConfig } from '../types.js';\nimport { getLogger } from '../logger.js';\nimport { notInstalled } from '../db/postgres.js';\nimport { parseRedisUrl } from '../tasks/bullmq-backend.js';\nimport { connectPrimaryCache } from './ipc.js';\n\n// A small key/value cache with two backends:\n// - redis: shared by every worker and instance — what production wants.\n// - memory: in-process; under clustering the primary holds it and workers reach it\n// over IPC, so it's shared by all workers on the machine (not across machines).\n// Values are JSON-serialised. A Redis outage degrades to cache misses instead of\n// failing the request — a cache must never be the thing that takes the API down.\n\nexport interface Backend {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ttlSeconds: number | undefined): Promise<void>;\n del(keys: string[]): Promise<number>;\n clear(prefix: string): Promise<number>;\n close(): Promise<void>;\n}\n\nexport function memoryBackend(maxEntries: number): Backend {\n const store = new Map<string, { value: string; expires: number }>();\n const live = (key: string) => {\n const hit = store.get(key);\n if (!hit) return undefined;\n if (hit.expires !== 0 && hit.expires <= Date.now()) {\n store.delete(key);\n return undefined;\n }\n return hit;\n };\n return {\n async get(key) {\n const hit = live(key);\n if (!hit) return null;\n // Re-insert so Map order tracks recency (LRU eviction drops the oldest).\n store.delete(key);\n store.set(key, hit);\n return hit.value;\n },\n async set(key, value, ttl) {\n store.delete(key);\n store.set(key, { value, expires: ttl ? Date.now() + ttl * 1000 : 0 });\n while (store.size > maxEntries) store.delete(store.keys().next().value!);\n },\n async del(keys) {\n let n = 0;\n for (const k of keys) if (live(k) && store.delete(k)) n++;\n return n;\n },\n async clear(prefix) {\n let n = 0;\n for (const k of [...store.keys()]) if (k.startsWith(prefix) && store.delete(k)) n++;\n return n;\n },\n async close() {\n store.clear();\n },\n };\n}\n\nasync function redisBackend(url: string, timeout: number): Promise<Backend> {\n let Redis: new (opts: RedisOptions) => RedisClient;\n try {\n const mod = (await import('ioredis')) as unknown as {\n Redis?: typeof Redis;\n default?: typeof Redis;\n };\n Redis = (mod.Redis ?? mod.default)!;\n } catch (err) {\n throw notInstalled(err, 'ioredis', 'npm install ioredis');\n }\n const client = new Redis({\n ...parseRedisUrl(url),\n // Fail fast instead of queueing commands while disconnected; callers treat\n // a rejected command as a miss.\n enableOfflineQueue: false,\n maxRetriesPerRequest: 1,\n commandTimeout: timeout,\n });\n let lastWarn = 0;\n client.on('error', (err: Error) => {\n // Reconnect attempts emit an error each time — log at most every 30 s.\n if (Date.now() - lastWarn > 30_000) {\n lastWarn = Date.now();\n getLogger().warn(`Cache Redis unavailable: ${err.message} (serving cache misses)`);\n }\n });\n\n // Wait for the first connection so writes made right after boot aren't dropped (the\n // offline queue is off), but never longer than a few timeouts: an unreachable Redis\n // must not block startup — the cache just serves misses until it comes back.\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.max(2000, timeout * 2));\n client.once('ready', () => {\n clearTimeout(timer);\n resolve();\n });\n });\n return {\n get: (key) => client.get(key),\n async set(key, value, ttl) {\n if (ttl) await client.set(key, value, 'EX', Math.max(1, Math.ceil(ttl)));\n else await client.set(key, value);\n },\n del: (keys) => (keys.length ? client.del(...keys) : Promise.resolve(0)),\n async clear(prefix) {\n let n = 0;\n let cursor = '0';\n const match = prefix.replace(/[*?[\\]\\\\]/g, '\\\\$&') + '*';\n do {\n const [next, keys] = await client.scan(cursor, 'MATCH', match, 'COUNT', 500);\n cursor = next;\n if (keys.length) n += await client.unlink(...keys);\n } while (cursor !== '0');\n return n;\n },\n async close() {\n await client.quit().catch(() => client.disconnect());\n },\n };\n}\n\nlet backend: Backend | null = null;\nlet prefix = 'efc:';\nlet revocationFailure: 'reject' | 'allow' = 'reject';\n\n/** How requireAuth should treat a failed revocation check — see CacheConfig. */\nexport function revocationFailureMode(): 'reject' | 'allow' {\n return revocationFailure;\n}\nconst pending = new Map<string, Promise<unknown>>();\n\nexport async function configureCache(config: CacheConfig): Promise<void> {\n await closeCache();\n prefix = config.prefix ?? 'efc:';\n revocationFailure = config.onRevocationCheckError ?? 'reject';\n if (config.backend === 'redis') {\n backend = await redisBackend(config.url ?? 'redis://localhost:6379', config.timeout ?? 1000);\n } else if (cluster.isWorker) {\n // Cluster workers share the primary's store over IPC (see cache/ipc.ts).\n backend = (await connectPrimaryCache()) ?? memoryBackend(config.maxEntries ?? 10_000);\n } else {\n backend = memoryBackend(config.maxEntries ?? 10_000);\n }\n}\n\nexport function isCacheConfigured(): boolean {\n return backend !== null;\n}\n\nexport async function closeCache(): Promise<void> {\n const b = backend;\n backend = null;\n pending.clear();\n await b?.close();\n}\n\nfunction requireBackend(): Backend {\n if (!backend) throw new Error('[EFC] Cache not configured — pass cache: { backend } to ignite()');\n return backend;\n}\n\n// Backend errors (Redis down/slow) degrade to \"no cache\" rather than failing the caller.\nasync function safely<T>(op: string, fn: (b: Backend) => Promise<T>, fallback: T): Promise<T> {\n const b = requireBackend();\n try {\n return await fn(b);\n } catch (err) {\n getLogger().debug({ err }, `cache ${op} failed`);\n return fallback;\n }\n}\n\nexport interface CacheSetOptions {\n /** Seconds until the entry expires. Omit for no expiry. */\n ttl?: number;\n}\n\nexport interface Cache {\n /** The cached value, or `undefined` on a miss (or when the backend is unreachable). */\n get<T = unknown>(key: string): Promise<T | undefined>;\n set(key: string, value: unknown, options?: CacheSetOptions): Promise<void>;\n has(key: string): Promise<boolean>;\n /** Deletes keys; returns how many existed. */\n del(...keys: string[]): Promise<number>;\n /**\n * Returns the cached value, or runs `fn`, caches its result and returns it.\n * Concurrent calls for the same key in one process share a single `fn` run.\n * `undefined` results are not cached.\n */\n wrap<T>(key: string, options: CacheSetOptions | number, fn: () => Promise<T>): Promise<T>;\n /** Deletes every key starting with `keyPrefix` (all of this app's keys when omitted). */\n clear(keyPrefix?: string): Promise<number>;\n}\n\nexport const cache: Cache = {\n async get<T>(key: string) {\n const raw = await safely('get', (b) => b.get(prefix + key), null);\n return raw === null ? undefined : (JSON.parse(raw) as T);\n },\n async set(key, value, options) {\n if (value === undefined) return;\n await safely('set', (b) => b.set(prefix + key, JSON.stringify(value), options?.ttl), undefined);\n },\n async has(key) {\n return (await safely('get', (b) => b.get(prefix + key), null)) !== null;\n },\n async del(...keys) {\n return safely('del', (b) => b.del(keys.map((k) => prefix + k)), 0);\n },\n async wrap<T>(key: string, options: CacheSetOptions | number, fn: () => Promise<T>) {\n const hit = await cache.get<T>(key);\n if (hit !== undefined) return hit;\n const inflight = pending.get(key) as Promise<T> | undefined;\n if (inflight) return inflight;\n const run = (async () => {\n try {\n const value = await fn();\n await cache.set(key, value, typeof options === 'number' ? { ttl: options } : options);\n return value;\n } finally {\n pending.delete(key);\n }\n })();\n pending.set(key, run);\n return run;\n },\n async clear(keyPrefix = '') {\n return safely('clear', (b) => b.clear(prefix + keyPrefix), 0);\n },\n};\n\n/** For auth's revocation checks, which must distinguish \"absent\" from \"backend down\". */\nexport async function rawGet(key: string): Promise<string | null> {\n return requireBackend().get(prefix + key);\n}\n\nexport async function rawSet(key: string, value: string, ttlSeconds: number): Promise<void> {\n await requireBackend().set(prefix + key, value, ttlSeconds);\n}\n","import cluster, { type Worker } from 'node:cluster';\nimport { randomUUID } from 'node:crypto';\nimport type { Backend } from './index.js';\nimport { memoryBackend } from './index.js';\nimport { getLogger } from '../logger.js';\n\n// The memory cache under clustering: the primary owns the only store and answers\n// workers' requests over the cluster IPC channel, so every worker sees the same\n// entries and the same revoked sessions. Message shape is tagged to avoid clashing\n// with application IPC.\n\nconst TAG = '__efcCache';\nconst TIMEOUT_MS = 2000;\n\ntype Op = 'ping' | 'get' | 'set' | 'del' | 'clear';\ninterface Request {\n [TAG]: true;\n id: string;\n op: Op;\n args: unknown[];\n}\ninterface Response {\n [TAG]: true;\n id: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n}\n\nconst isTagged = (msg: unknown): msg is Record<string, unknown> =>\n msg !== null && typeof msg === 'object' && (msg as Record<string, unknown>)[TAG] === true;\n\n/** Primary side: hold the store and serve every worker. Called before workers fork. */\nexport function servePrimaryCache(maxEntries: number): void {\n const store = memoryBackend(maxEntries);\n cluster.on('message', (worker: Worker, msg: unknown) => {\n if (!isTagged(msg)) return;\n const req = msg as unknown as Request;\n const run = async (): Promise<unknown> => {\n switch (req.op) {\n case 'ping':\n return 'pong';\n case 'get':\n return store.get(req.args[0] as string);\n case 'set':\n return store.set(\n req.args[0] as string,\n req.args[1] as string,\n req.args[2] as number | undefined,\n );\n case 'del':\n return store.del(req.args[0] as string[]);\n case 'clear':\n return store.clear(req.args[0] as string);\n }\n };\n run().then(\n (result) =>\n worker.isConnected() &&\n worker.send({ [TAG]: true, id: req.id, ok: true, result } satisfies Response),\n (err: unknown) =>\n worker.isConnected() &&\n worker.send({ [TAG]: true, id: req.id, ok: false, error: String(err) } satisfies Response),\n );\n });\n}\n\n/**\n * Worker side: a Backend that forwards to the primary. Resolves to null — so the caller\n * can fall back to a local store — when no EFC primary answers (e.g. the app runs its\n * own cluster primary instead of ignite()'s).\n */\nexport async function connectPrimaryCache(): Promise<Backend | null> {\n if (!process.send) return null;\n const pending = new Map<\n string,\n { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }\n >();\n const onMessage = (msg: unknown) => {\n if (!isTagged(msg)) return;\n const res = msg as unknown as Response;\n const p = pending.get(res.id);\n if (!p) return;\n pending.delete(res.id);\n clearTimeout(p.timer);\n if (res.ok) p.resolve(res.result);\n else p.reject(new Error(res.error));\n };\n process.on('message', onMessage);\n\n const call = (op: Op, ...args: unknown[]) =>\n new Promise<unknown>((resolve, reject) => {\n const id = randomUUID();\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new Error(`[EFC] cache IPC \"${op}\" timed out`));\n }, TIMEOUT_MS);\n timer.unref();\n pending.set(id, { resolve, reject, timer });\n process.send!({ [TAG]: true, id, op, args } satisfies Request);\n });\n\n try {\n await call('ping');\n } catch {\n process.off('message', onMessage);\n getLogger().warn(\n 'cache backend \"memory\": no EFC cluster primary answered — using a per-worker store (entries and revoked sessions are not shared)',\n );\n return null;\n }\n\n return {\n get: async (key) => (await call('get', key)) as string | null,\n set: async (key, value, ttl) => {\n await call('set', key, value, ttl);\n },\n del: async (keys) => (await call('del', keys)) as number,\n clear: async (prefix) => (await call('clear', prefix)) as number,\n close: async () => {\n process.off('message', onMessage);\n for (const p of pending.values()) clearTimeout(p.timer);\n pending.clear();\n },\n };\n}\n"]}
|