All files / routes invitations.ts

95.91% Statements 94/98
100% Branches 59/59
100% Functions 4/4
95.91% Lines 94/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297                                                        1x     1x 7x 7x 7x 7x   7x 7x 1x     6x 1x     5x 1x                 4x     4x       7x                               1x 8x 8x 8x 8x   8x 8x 1x     7x   7x 7x 1x     6x 1x     5x 1x               4x 2x     2x 2x 1x     1x   1x             1x 6x 6x 6x 1x     5x 5x 5x   5x 5x 1x       4x 1x       3x 1x                 2x 2x   2x                           1x 11x 11x 11x 1x     10x 10x 10x   10x 10x 1x       9x 1x       8x 1x                 7x 2x                 5x       5x   1x 1x                 4x 4x       2x     2x         1x 1x 1x 1x   1x                       3x     3x               3x 3x     3x     3x   3x                      
// Team Invitation Acceptance (requires auth but not pro access)
 
import { Hono } from "hono";
import type { Dal } from "../dal";
import { createDal } from "../dal";
import { getDb } from "../db";
import { createDualCache, type DualCache } from "../lib/cache";
import { error, success, handleError } from "../lib/response";
import { invalidateUserRoles } from "../lib/role-cache";
import type { Services } from "../services";
import { ProService } from "../services";
 
type AuthUser = { id: string; name: string; email: string };
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: AuthUser | null;
		session: unknown;
		dal: Dal;
		services: Services;
		db: ReturnType<typeof getDb>;
		cache: DualCache;
		proId: string;
		proRole: string;
	};
};
 
const invitations = new Hono<Env>();
 
// Preview invitation details (no auth required - for smart accept flow)
invitations.get("/:token/preview", async (c) => {
	try {
		const token = c.req.param("token");
		const db = getDb(c.env.DB);
		const dal = createDal(db);
 
		const invitation = await dal.teamInvitations.findByToken(token);
		if (!invitation) {
			return error(c, "NOT_FOUND", "Invitation not found", 404);
		}
 
		if (new Date() > invitation.expiresAt) {
			return error(c, "EXPIRED", "Invitation has expired", 400);
		}
 
		if (invitation.acceptedAt) {
			return error(
				c,
				"ALREADY_ACCEPTED",
				"Invitation has already been accepted",
				400,
			);
		}
 
		// Get pro name for context
		const pro = await dal.pros.findById(invitation.proId);
 
		// Check if the invited email already has an account
		const existingUser = invitation.email
			? await dal.users.findByEmail(invitation.email)
			: null;
 
		return success(c, {
			email: invitation.email,
			phone: invitation.phone,
			role: invitation.role,
			proName: pro?.businessName || "Unknown",
			expiresAt: invitation.expiresAt,
			accountExists: !!existingUser,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Verify signup for invited users (no auth required)
// Called after registration to auto-verify email, skipping the verification email step.
// Security: token (192-bit entropy) + email match = equivalent to email verification.
invitations.post("/:token/verify-signup", async (c) => {
	try {
		const token = c.req.param("token");
		const db = getDb(c.env.DB);
		const dal = createDal(db);
 
		const body = await c.req.json<{ email: string }>();
		if (!body.email) {
			return error(c, "MISSING_EMAIL", "Email is required", 400);
		}
 
		const email = body.email.toLowerCase().trim();
 
		const invitation = await dal.teamInvitations.findByToken(token);
		if (!invitation) {
			return error(c, "NOT_FOUND", "Invitation not found", 404);
		}
 
		if (new Date() > invitation.expiresAt) {
			return error(c, "EXPIRED", "Invitation has expired", 400);
		}
 
		if (invitation.acceptedAt) {
			return error(
				c,
				"ALREADY_ACCEPTED",
				"Invitation has already been accepted",
				400,
			);
		}
 
		if (!invitation.email || invitation.email.toLowerCase() !== email) {
			return error(c, "EMAIL_MISMATCH", "Email does not match invitation", 403);
		}
 
		const user = await dal.users.findByEmail(email);
		if (!user) {
			return error(c, "NOT_FOUND", "User not found", 404);
		}
 
		await dal.users.update(user.id, { emailVerified: true });
 
		return success(c, { verified: true });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get invitation details by token
invitations.get("/:token", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const token = c.req.param("token");
		const db = getDb(c.env.DB);
		const dal = createDal(db);
 
		const invitation = await dal.teamInvitations.findByToken(token);
		if (!invitation) {
			return error(c, "NOT_FOUND", "Invitation not found", 404);
		}
 
		// Check if expired
		if (new Date() > invitation.expiresAt) {
			return error(c, "EXPIRED", "Invitation has expired", 400);
		}
 
		// Check if already accepted
		if (invitation.acceptedAt) {
			return error(
				c,
				"ALREADY_ACCEPTED",
				"Invitation has already been accepted",
				400,
			);
		}
 
		// Get pro details
		const pro = await dal.pros.findById(invitation.proId);
		const inviter = await dal.users.findById(invitation.invitedBy);
 
		return success(c, {
			id: invitation.id,
			email: invitation.email,
			role: invitation.role,
			pro: pro ? { id: pro.id, businessName: pro.businessName } : null,
			invitedBy: inviter ? { id: inviter.id, name: inviter.name } : null,
			expiresAt: invitation.expiresAt,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Accept an invitation
invitations.post("/:token/accept", async (c) => {
	try {
		const user = c.get("user");
		if (!user) {
			return error(c, "UNAUTHORIZED", "Authentication required", 401);
		}
 
		const token = c.req.param("token");
		const db = getDb(c.env.DB);
		const dal = createDal(db);
 
		const invitation = await dal.teamInvitations.findByToken(token);
		if (!invitation) {
			return error(c, "NOT_FOUND", "Invitation not found", 404);
		}
 
		// Check if expired
		if (new Date() > invitation.expiresAt) {
			return error(c, "EXPIRED", "Invitation has expired", 400);
		}
 
		// Check if already accepted
		if (invitation.acceptedAt) {
			return error(
				c,
				"ALREADY_ACCEPTED",
				"Invitation has already been accepted",
				400,
			);
		}
 
		// Check if the invitation email matches the logged-in user's email
		if (!invitation.email || user.email.toLowerCase() !== invitation.email.toLowerCase()) {
			return error(
				c,
				"EMAIL_MISMATCH",
				"This invitation was sent to a different email address. Please log in with the correct account.",
				403,
			);
		}
 
		// Check if user already has a role for this pro
		const existingRole = await dal.userTenantRoles.findUserProRole(
			user.id,
			invitation.proId,
		);
		if (existingRole) {
			// Mark invitation as accepted but don't create duplicate role
			await dal.teamInvitations.markAccepted(invitation.id);
			return error(
				c,
				"ALREADY_MEMBER",
				"You are already a member of this team",
				400,
			);
		}
 
		// Safety net: check if user already belongs to any pro (may have joined between invite and accept)
		const proRoles = await dal.userTenantRoles.findProRoles(user.id);
		if (proRoles.length > 0) {
			/* v8 ignore start -- V8 artifact: ?? fallback */
			const existingProId = proRoles[0].tenantId ?? "";
			/* v8 ignore stop */
			const existingPro = await dal.pros.findById(existingProId);
 
			// If it's a fresh auto-created draft (never used), clean it up and proceed
			if (
				existingPro &&
				existingPro.status === "draft" &&
				existingPro.onboardingStatus === "not_started"
			) {
				const proService = new ProService(dal);
				await proService.delete(existingProId);
				const cleanupCache = createDualCache(c.env.KV_CACHE);
				await invalidateUserRoles(cleanupCache, user.id);
			} else {
				return error(
					c,
					"ALREADY_IN_PRO",
					"You are already part of another organization. Each user can only belong to one pro.",
					409,
				);
			}
		}
 
		// Mark email as verified — the user proved ownership by receiving the
		// invitation at this address, so requiring a separate verification email
		// is unnecessary friction.
		await dal.users.update(user.id, { emailVerified: true });
 
		// Create the role
		const newRole = await dal.userTenantRoles.create({
			userId: user.id,
			tenantType: "pro",
			tenantId: invitation.proId,
			role: invitation.role,
		});
 
		// Invalidate cached roles for the user who accepted the invitation
		const invitationCache = createDualCache(c.env.KV_CACHE);
		await invalidateUserRoles(invitationCache, user.id);
 
		// Mark invitation as accepted
		await dal.teamInvitations.markAccepted(invitation.id);
 
		// Get pro details
		const pro = await dal.pros.findById(invitation.proId);
 
		return success(c, {
			message: "Invitation accepted successfully",
			role: newRole.role,
			pro: pro ? { id: pro.id, businessName: pro.businessName } : null,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default invitations;