invitations.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. import { Router, Request, Response } from 'express';
  2. import { randomBytes } from 'crypto';
  3. import { prisma } from '../lib/prisma';
  4. import { authMiddleware, optionalAuth } from '../lib/auth';
  5. import { sendInviteEmail } from '../lib/email';
  6. const router = Router();
  7. const INVITE_EXPIRY_DAYS = 7;
  8. const INVITE_EXPIRY_MS = INVITE_EXPIRY_DAYS * 24 * 60 * 60 * 1000;
  9. // Frontend base URL used to build full invite links
  10. const FRONTEND_URL = process.env.FRONTEND_URL || process.env.NEXT_PUBLIC_API_URL?.replace('/api', '') || 'http://localhost:3000';
  11. function buildInviteUrl(token: string): string {
  12. return `${FRONTEND_URL.replace(/\/$/, '')}/invite/${token}`;
  13. }
  14. function str(v: string | string[] | undefined): string {
  15. return Array.isArray(v) ? v[0] ?? '' : (v ?? '');
  16. }
  17. // ── Helpers ───────────────────────────────────────────────────────────────────
  18. /** Check if current user can invite to this project (projectId must not be null) */
  19. async function canInvite(projectId: string, userId: string): Promise<boolean> {
  20. const member = await prisma.projectMember.findFirst({
  21. where: { projectId, userId },
  22. });
  23. return !!member && (member.role === 'ADMIN' || member.role === 'EDITOR');
  24. }
  25. /** Auto-expire stale invitations */
  26. async function expireOldInvitations() {
  27. await prisma.invitation.updateMany({
  28. where: {
  29. status: 'PENDING',
  30. expiresAt: { lt: new Date() },
  31. },
  32. data: { status: 'EXPIRED' },
  33. });
  34. }
  35. // ── GET /api/invitations/:token ─ public verify (no auth needed) ───────────────
  36. router.get('/:token', optionalAuth, async (req: Request, res: Response) => {
  37. try {
  38. await expireOldInvitations();
  39. const invitation = await prisma.invitation.findUnique({
  40. where: { token: str(req.params.token) },
  41. include: {
  42. project: { select: { id: true, name: true } },
  43. },
  44. });
  45. if (!invitation) {
  46. res.status(404).json({ error: 'Invitation not found' });
  47. return;
  48. }
  49. // If user is logged in, check if this is their invitation
  50. const isOwnInvitation = req.user?.email === invitation.email;
  51. // Workspace invites (projectId=null) have no project membership to check
  52. let alreadyMember = false;
  53. if (req.user) {
  54. if (invitation.projectId === null) {
  55. // Workspace invite: user is a member if they already exist as MEMBER/ADMIN
  56. const existingUser = await prisma.user.findUnique({ where: { id: req.user.userId } });
  57. alreadyMember = !!(existingUser && existingUser.globalRole !== 'PROJECT_USER');
  58. } else {
  59. alreadyMember = !!(await prisma.projectMember.findFirst({
  60. where: { projectId: invitation.projectId!, userId: req.user.userId },
  61. }));
  62. }
  63. }
  64. // Check if the invite email already has an account (so frontend shows sign-in vs register)
  65. const inviteeExists = !!(await prisma.user.findUnique({
  66. where: { email: invitation.email },
  67. }));
  68. // Determine invite type for UI
  69. const isWorkspace = invitation.projectId === null;
  70. const type = isWorkspace ? 'WORKSPACE' : 'PROJECT';
  71. // Return full info even for expired/used — frontend shows appropriate UI
  72. res.json({
  73. invitation: {
  74. id: invitation.id,
  75. email: invitation.email,
  76. role: invitation.role,
  77. projectName: isWorkspace ? null : invitation.project?.name ?? null,
  78. projectId: invitation.projectId,
  79. expiresAt: invitation.expiresAt,
  80. status: invitation.status,
  81. isExpired: invitation.status === 'EXPIRED' || invitation.expiresAt < new Date(),
  82. isOwnInvitation,
  83. alreadyMember: alreadyMember || invitation.status === 'ACCEPTED',
  84. isLoggedIn: !!req.user,
  85. inviteeExists,
  86. type,
  87. },
  88. });
  89. } catch (err) {
  90. console.error('Verify invitation error:', err);
  91. res.status(500).json({ error: 'Internal server error' });
  92. }
  93. });
  94. // ── POST /api/invitations/:token/accept ─ public (no auth needed, but user must be logged in) ─
  95. router.post('/:token/accept', authMiddleware, async (req: Request, res: Response) => {
  96. try {
  97. await expireOldInvitations();
  98. const invitation = await prisma.invitation.findUnique({
  99. where: { token: str(req.params.token) },
  100. });
  101. if (!invitation) {
  102. res.status(404).json({ error: 'Invitation not found' });
  103. return;
  104. }
  105. if (invitation.status !== 'PENDING') {
  106. res.status(410).json({ error: `Invitation has been ${invitation.status.toLowerCase()}` });
  107. return;
  108. }
  109. if (invitation.expiresAt < new Date()) {
  110. res.status(410).json({ error: 'Invitation has expired' });
  111. return;
  112. }
  113. if (invitation.email !== req.user!.email) {
  114. res.status(403).json({ error: 'This invitation was sent to a different email address' });
  115. return;
  116. }
  117. // Workspace invite (projectId=null) — no project membership to create; just accept it
  118. if (invitation.projectId === null) {
  119. await prisma.invitation.update({
  120. where: { id: invitation.id },
  121. data: { status: 'ACCEPTED' },
  122. });
  123. res.json({ message: 'Invitation accepted', projectId: null });
  124. return;
  125. }
  126. // Check if already a member
  127. const existing = await prisma.projectMember.findFirst({
  128. where: { projectId: invitation.projectId, userId: req.user!.userId },
  129. });
  130. if (existing) {
  131. // Mark invitation as accepted anyway
  132. await prisma.invitation.update({
  133. where: { id: invitation.id },
  134. data: { status: 'ACCEPTED' },
  135. });
  136. res.json({ message: 'Already a member', projectId: invitation.projectId });
  137. return;
  138. }
  139. // Create membership + mark invitation accepted (transaction)
  140. const [member] = await prisma.$transaction([
  141. prisma.projectMember.create({
  142. data: {
  143. userId: req.user!.userId,
  144. projectId: invitation.projectId,
  145. role: invitation.role,
  146. invitedBy: invitation.invitedBy,
  147. },
  148. include: {
  149. project: { select: { id: true, name: true } },
  150. },
  151. }),
  152. prisma.invitation.update({
  153. where: { id: invitation.id },
  154. data: { status: 'ACCEPTED' },
  155. }),
  156. ]);
  157. res.json({ member });
  158. } catch (err) {
  159. console.error('Accept invitation error:', err);
  160. res.status(500).json({ error: 'Internal server error' });
  161. }
  162. });
  163. // ── Project-scoped invitation routes (require auth + project membership) ───────
  164. // GET /api/projects/:projectId/invitations — list pending invitations
  165. router.get('/project/:projectId', authMiddleware, async (req: Request, res: Response) => {
  166. try {
  167. const projectId = str(req.params.projectId);
  168. if (!(await canInvite(projectId, req.user!.userId))) {
  169. res.status(403).json({ error: 'Forbidden' });
  170. return;
  171. }
  172. await expireOldInvitations();
  173. const invitations = await prisma.invitation.findMany({
  174. where: { projectId },
  175. orderBy: { createdAt: 'desc' },
  176. });
  177. res.json({ invitations });
  178. } catch (err) {
  179. console.error('List invitations error:', err);
  180. res.status(500).json({ error: 'Internal server error' });
  181. }
  182. });
  183. // POST /api/projects/:projectId/invitations — create invitation
  184. router.post('/project/:projectId', authMiddleware, async (req: Request, res: Response) => {
  185. try {
  186. const projectId = str(req.params.projectId);
  187. if (!(await canInvite(projectId, req.user!.userId))) {
  188. res.status(403).json({ error: 'Forbidden — must be admin or editor' });
  189. return;
  190. }
  191. const { email, role = 'REVIEWER' } = req.body as { email: string; role?: string };
  192. if (!email) {
  193. res.status(400).json({ error: 'Email is required' });
  194. return;
  195. }
  196. const validRoles = ['ADMIN', 'EDITOR', 'REVIEWER', 'VIEWER'];
  197. if (!validRoles.includes(role)) {
  198. res.status(400).json({ error: 'Invalid role' });
  199. return;
  200. }
  201. // Check if already a member
  202. const existingMember = await prisma.user.findUnique({ where: { email } });
  203. if (existingMember) {
  204. const member = await prisma.projectMember.findFirst({
  205. where: { projectId, userId: existingMember.id },
  206. });
  207. if (member) {
  208. res.status(409).json({ error: 'User is already a member of this project' });
  209. return;
  210. }
  211. }
  212. // Check if there's already a pending invitation
  213. const existingInvite = await prisma.invitation.findFirst({
  214. where: { projectId, email, status: 'PENDING' },
  215. });
  216. if (existingInvite) {
  217. res.status(409).json({ error: 'A pending invitation already exists for this email' });
  218. return;
  219. }
  220. const token = randomBytes(32).toString('hex');
  221. const expiresAt = new Date(Date.now() + INVITE_EXPIRY_MS);
  222. const invitation = await prisma.invitation.create({
  223. data: {
  224. email,
  225. projectId,
  226. role: role as any,
  227. token,
  228. invitedBy: req.user!.userId,
  229. expiresAt,
  230. },
  231. });
  232. // Return full invite URL
  233. const inviteUrl = buildInviteUrl(token);
  234. // Send invite email (skipped for .local domains or if RESEND_API_KEY not set)
  235. const project = await prisma.project.findUnique({ where: { id: projectId }, select: { name: true } });
  236. await sendInviteEmail({
  237. to: email,
  238. projectName: project?.name,
  239. role,
  240. expiresDays: INVITE_EXPIRY_DAYS,
  241. inviteUrl,
  242. type: 'PROJECT',
  243. });
  244. res.status(201).json({ invitation, inviteUrl });
  245. } catch (err) {
  246. console.error('Create invitation error:', err);
  247. res.status(500).json({ error: 'Internal server error' });
  248. }
  249. });
  250. // ── Admin: workspace-wide MEMBER invite ──────────────────────────────────────────
  251. // POST /api/invitations/workspace — admin: invite a MEMBER to the workspace (no project)
  252. // User registers → globalRole = MEMBER, can create their own projects
  253. router.post('/workspace', authMiddleware, async (req: Request, res: Response) => {
  254. try {
  255. if (req.user!.globalRole !== 'ADMIN') {
  256. res.status(403).json({ error: 'Admin access required' });
  257. return;
  258. }
  259. const { email } = req.body as { email: string };
  260. if (!email) {
  261. res.status(400).json({ error: 'email is required' });
  262. return;
  263. }
  264. // If user already exists with MEMBER or ADMIN role, just return existing info
  265. const existingUser = await prisma.user.findUnique({ where: { email } });
  266. if (existingUser) {
  267. res.status(409).json({
  268. error: `User already exists as ${existingUser.globalRole}. No invitation needed.`,
  269. user: { id: existingUser.id, email: existingUser.email, globalRole: existingUser.globalRole }
  270. });
  271. return;
  272. }
  273. // Revoke any existing pending workspace invite for this email
  274. await prisma.invitation.updateMany({
  275. where: { email, projectId: null as any, status: 'PENDING' },
  276. data: { status: 'REVOKED' },
  277. });
  278. const token = randomBytes(32).toString('hex');
  279. const expiresAt = new Date(Date.now() + INVITE_EXPIRY_MS);
  280. // projectId = null means workspace invite (creates MEMBER)
  281. const invitation = await prisma.invitation.create({
  282. data: {
  283. email,
  284. projectId: null, // null = workspace invite
  285. role: 'REVIEWER', // Role enum used for display; type=WORKSPACE means MEMBER on register
  286. token,
  287. invitedBy: req.user!.userId,
  288. expiresAt,
  289. } as any,
  290. });
  291. const inviteUrl = buildInviteUrl(token);
  292. // Send invite email (skipped for .local domains or if RESEND_API_KEY not set)
  293. await sendInviteEmail({
  294. to: email,
  295. projectName: null,
  296. role: 'MEMBER',
  297. expiresDays: INVITE_EXPIRY_DAYS,
  298. inviteUrl,
  299. type: 'WORKSPACE',
  300. });
  301. res.status(201).json({ invitation, inviteUrl });
  302. } catch (err) {
  303. console.error('Workspace invite error:', err);
  304. res.status(500).json({ error: 'Internal server error' });
  305. }
  306. });
  307. // POST /api/invitations — project-scoped invite (PROJECT_USER)
  308. // Admin or project member: invite by email to a specific project
  309. router.post('/', authMiddleware, async (req: Request, res: Response) => {
  310. try {
  311. const { email, projectId, role = 'REVIEWER' } = req.body as {
  312. email: string;
  313. projectId: string;
  314. role?: string;
  315. };
  316. if (!email || !projectId) {
  317. res.status(400).json({ error: 'email and projectId are required' });
  318. return;
  319. }
  320. const validRoles = ['ADMIN', 'EDITOR', 'REVIEWER', 'VIEWER'];
  321. if (!validRoles.includes(role)) {
  322. res.status(400).json({ error: 'Invalid role' });
  323. return;
  324. }
  325. // Check permission: admin OR project ADMIN/EDITOR
  326. const isAdmin = req.user!.globalRole === 'ADMIN';
  327. if (!isAdmin && !(await canInvite(projectId, req.user!.userId))) {
  328. res.status(403).json({ error: 'Forbidden' });
  329. return;
  330. }
  331. // Verify project exists
  332. const project = await prisma.project.findUnique({ where: { id: projectId } });
  333. if (!project) {
  334. res.status(404).json({ error: 'Project not found' });
  335. return;
  336. }
  337. // Check if already a member
  338. const existingMember = await prisma.user.findUnique({ where: { email } });
  339. if (existingMember) {
  340. const member = await prisma.projectMember.findFirst({
  341. where: { projectId, userId: existingMember.id },
  342. });
  343. if (member) {
  344. res.status(409).json({ error: 'User is already a member of this project' });
  345. return;
  346. }
  347. }
  348. // Revoke any existing pending invite for this email+project
  349. await prisma.invitation.updateMany({
  350. where: { projectId, email, status: 'PENDING' },
  351. data: { status: 'REVOKED' },
  352. });
  353. const token = randomBytes(32).toString('hex');
  354. const expiresAt = new Date(Date.now() + INVITE_EXPIRY_MS);
  355. const invitation = await prisma.invitation.create({
  356. data: {
  357. email,
  358. projectId,
  359. role: role as any,
  360. token,
  361. invitedBy: req.user!.userId,
  362. expiresAt,
  363. },
  364. });
  365. const inviteUrl = buildInviteUrl(token);
  366. // Send invite email (skipped for .local domains or if RESEND_API_KEY not set)
  367. await sendInviteEmail({
  368. to: email,
  369. projectName: project.name,
  370. role,
  371. expiresDays: INVITE_EXPIRY_DAYS,
  372. inviteUrl,
  373. type: 'PROJECT',
  374. });
  375. res.status(201).json({ invitation, inviteUrl });
  376. } catch (err) {
  377. console.error('Admin invite error:', err);
  378. res.status(500).json({ error: 'Internal server error' });
  379. }
  380. });
  381. // GET /api/invitations — admin: list all pending invitations (workspace + project)
  382. router.get('/', authMiddleware, async (req: Request, res: Response) => {
  383. try {
  384. if (req.user!.globalRole !== 'ADMIN') {
  385. res.status(403).json({ error: 'Admin access required' });
  386. return;
  387. }
  388. const invitations = await prisma.invitation.findMany({
  389. where: { status: 'PENDING' },
  390. include: {
  391. project: { select: { id: true, name: true } },
  392. },
  393. orderBy: { createdAt: 'desc' },
  394. });
  395. // Mark workspace invites (projectId=null) with type='WORKSPACE'
  396. const typed = invitations.map(inv => ({
  397. ...inv,
  398. type: inv.projectId === null ? 'WORKSPACE' as const : 'PROJECT' as const,
  399. }));
  400. res.json({ invitations: typed });
  401. } catch (err) {
  402. console.error('List invitations error:', err);
  403. res.status(500).json({ error: 'Internal server error' });
  404. }
  405. });
  406. // DELETE /api/invitations/:id — revoke invitation (admin or project admin/editor)
  407. router.delete('/:id', authMiddleware, async (req: Request, res: Response) => {
  408. try {
  409. const invitation = await prisma.invitation.findUnique({
  410. where: { id: str(req.params.id) },
  411. });
  412. if (!invitation) {
  413. res.status(404).json({ error: 'Invitation not found' });
  414. return;
  415. }
  416. const isAdmin = req.user!.globalRole === 'ADMIN';
  417. // Workspace invites (projectId=null) can only be revoked by ADMIN
  418. if (!isAdmin && (invitation.projectId === null || !(await canInvite(invitation.projectId, req.user!.userId)))) {
  419. res.status(403).json({ error: 'Forbidden' });
  420. return;
  421. }
  422. if (invitation.status !== 'PENDING') {
  423. res.status(400).json({ error: 'Can only revoke pending invitations' });
  424. return;
  425. }
  426. await prisma.invitation.update({
  427. where: { id: invitation.id },
  428. data: { status: 'REVOKED' },
  429. });
  430. res.json({ message: 'Invitation revoked' });
  431. } catch (err) {
  432. console.error('Revoke invitation error:', err);
  433. res.status(500).json({ error: 'Internal server error' });
  434. }
  435. });
  436. // Resend invitation — create new token for same email (project admin/editor)
  437. router.post('/project/:projectId/resend', authMiddleware, async (req: Request, res: Response) => {
  438. try {
  439. const projectId = str(req.params.projectId);
  440. const isAdmin = req.user!.globalRole === 'ADMIN';
  441. if (!isAdmin && !(await canInvite(projectId, req.user!.userId))) {
  442. res.status(403).json({ error: 'Forbidden' });
  443. return;
  444. }
  445. const { invitationId } = req.body as { invitationId: string };
  446. if (!invitationId) {
  447. res.status(400).json({ error: 'invitationId required' });
  448. return;
  449. }
  450. const existing = await prisma.invitation.findUnique({ where: { id: invitationId } });
  451. if (!existing || existing.projectId !== projectId) {
  452. res.status(404).json({ error: 'Invitation not found' });
  453. return;
  454. }
  455. const token = randomBytes(32).toString('hex');
  456. const expiresAt = new Date(Date.now() + INVITE_EXPIRY_MS);
  457. const invitation = await prisma.invitation.update({
  458. where: { id: invitationId },
  459. data: { token, expiresAt, status: 'PENDING' },
  460. });
  461. res.json({ invitation, inviteUrl: buildInviteUrl(token) });
  462. } catch (err) {
  463. console.error('Resend invitation error:', err);
  464. res.status(500).json({ error: 'Internal server error' });
  465. }
  466. });
  467. export default router;