Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

14.1 KB
Raw Blame
import { createHash } from "node:crypto";
import { STRIPE_AVAILABLE } from "@cap/utils";
import { type ImageUpload, Organisation, User } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
import type { MySql2Database } from "drizzle-orm/mysql2";
import type { Adapter } from "next-auth/adapters";
import { nanoId } from "../helpers.ts";
import { enqueueLoopsSync } from "../loops/queue.ts";
import {
	accounts,
	organizationInvites,
	organizationMembers,
	organizations,
	sessions,
	users,
	verificationTokens,
} from "../schema.ts";
import type { ValidatedSsoIdentity } from "./sso.ts";
import { provisionStripeCustomer } from "./stripe-customer.ts";

const getAffectedRows = (result: unknown) => {
	if (Array.isArray(result)) {
		return (
			(result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0
		);
	}
	return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;
};

type CreateUserData = Parameters<NonNullable<Adapter["createUser"]>>[0];
type LinkAccountData = Parameters<NonNullable<Adapter["linkAccount"]>>[0];
type UnlinkAccountData = Parameters<NonNullable<Adapter["unlinkAccount"]>>[0];
type UpdateSessionData = Parameters<NonNullable<Adapter["updateSession"]>>[0];

function getProvisionedUserName(email: string) {
	return (
		email
			.split("@")[0]
			?.replace(/[._-]+/g, " ")
			.trim() || email
	);
}

async function hasPendingProvisionedInvite(
	db: MySql2Database,
	userId: User.UserId,
	email: string,
) {
	const [pendingInviteMember] = await db
		.select({ inviteId: organizationInvites.id })
		.from(organizationInvites)
		.innerJoin(
			organizationMembers,
			and(
				eq(
					organizationMembers.organizationId,
					organizationInvites.organizationId,
				),
				eq(organizationMembers.userId, userId),
			),
		)
		.where(
			and(
				eq(organizationInvites.invitedEmail, email),
				eq(organizationInvites.status, "pending"),
			),
		)
		.limit(1);

	return !!pendingInviteMember;
}

async function hasLinkedAccount(db: MySql2Database, userId: User.UserId) {
	const [linkedAccount] = await db
		.select({ id: accounts.id })
		.from(accounts)
		.where(eq(accounts.userId, userId))
		.limit(1);

	return !!linkedAccount;
}

export function DrizzleAdapter(
	db: MySql2Database,
	options?: { getSsoIdentity: () => ValidatedSsoIdentity | null },
): Adapter {
	return {
		async createUser(userData: CreateUserData) {
			const normalizedEmail = userData.email.toLowerCase();
			const ssoIdentity = options?.getSsoIdentity();
			if (ssoIdentity && ssoIdentity.email !== normalizedEmail) {
				throw new Error("The user does not match the verified SSO identity.");
			}
			let userId = User.UserId.make(nanoId());
			await db.transaction(async (tx) => {
				if (ssoIdentity) {
					const [organization] = await tx
						.select({ id: organizations.id })
						.from(organizations)
						.where(eq(organizations.id, ssoIdentity.organizationId))
						.for("update");
					if (!organization) throw new Error("SSO organization not found.");
				}
				const [existingUser] = await tx
					.select()
					.from(users)
					.where(eq(users.email, normalizedEmail))
					.limit(1);

				if (existingUser) {
					userId = existingUser.id;
					const userUpdate: Partial<typeof users.$inferInsert> = {};

					if (!existingUser.name && userData.name) {
						userUpdate.name = userData.name;
					}
					if (!existingUser.name && !userData.name) {
						userUpdate.name = getProvisionedUserName(normalizedEmail);
					}
					if (!existingUser.emailVerified && userData.emailVerified) {
						userUpdate.emailVerified = userData.emailVerified;
					}
					if (!existingUser.image && userData.image) {
						userUpdate.image = userData.image as ImageUpload.ImageUrlOrKey;
					}

					if (Object.keys(userUpdate).length > 0) {
						await tx.update(users).set(userUpdate).where(eq(users.id, userId));
					}

					await enqueueLoopsSync(tx, userId);
					return;
				}

				const [pendingInvite] = await tx
					.select({ id: organizationInvites.id })
					.from(organizationInvites)
					.where(
						and(
							eq(organizationInvites.invitedEmail, normalizedEmail),
							eq(organizationInvites.status, "pending"),
						),
					)
					.limit(1);

				const insertUser = tx.insert(users).values({
					id: userId,
					email: normalizedEmail,
					emailVerified: userData.emailVerified,
					name: userData.name,
					image: userData.image as ImageUpload.ImageUrlOrKey | null,
					activeOrganizationId: Organisation.OrganisationId.make(""),
					marketingOrigin:
						pendingInvite || ssoIdentity ? "teammate" : "independent",
				});
				if (ssoIdentity) {
					await insertUser.onDuplicateKeyUpdate({
						set: { email: normalizedEmail },
					});
					const [createdUser] = await tx
						.select({ id: users.id })
						.from(users)
						.where(eq(users.email, normalizedEmail))
						.limit(1);
					if (!createdUser) throw new Error("User was not created.");
					userId = createdUser.id;
				} else {
					await insertUser;
				}

				await enqueueLoopsSync(tx, userId);
				if (pendingInvite || ssoIdentity) {
					return;
				}

				const organizationId = Organisation.OrganisationId.make(nanoId());

				await tx.insert(organizations).values({
					id: organizationId,
					ownerId: userId,
					name: "My Organization",
				});

				await tx.insert(organizationMembers).values({
					id: nanoId(),
					organizationId,
					userId,
					role: "owner",
				});

				await tx
					.update(users)
					.set({
						activeOrganizationId: organizationId,
						defaultOrgId: organizationId,
					})
					.where(eq(users.id, userId));
			});

			const rows = await db
				.select()
				.from(users)
				.where(eq(users.id, userId))
				.limit(1);
			let row = rows[0];
			if (!row) throw new Error("User not found");

			if (STRIPE_AVAILABLE() && !ssoIdentity) {
				row = await provisionStripeCustomer(db, row);
			}

			return row;
		},
		async getUser(id) {
			const rows = await db
				.select()
				.from(users)
				.where(eq(users.id, User.UserId.make(id)))
				.limit(1);
			const row = rows[0];
			return row ?? null;
		},
		async getUserByEmail(email) {
			const normalizedEmail = email?.toLowerCase() ?? "";
			const rows = await db
				.select()
				.from(users)
				.where(eq(users.email, normalizedEmail))
				.limit(1)
				.catch((e) => {
					throw e;
				});
			const row = rows[0];
			if (!row) return null;

			if (
				!(await hasLinkedAccount(db, row.id)) &&
				(await hasPendingProvisionedInvite(db, row.id, normalizedEmail))
			) {
				return null;
			}

			return row;
		},
		async getUserByAccount({ providerAccountId, provider }) {
			const rows = await db
				.select()
				.from(users)
				.innerJoin(accounts, eq(users.id, accounts.userId))
				.where(
					and(
						eq(accounts.providerAccountId, providerAccountId),
						eq(accounts.provider, provider),
					),
				)
				.limit(1);
			const row = rows[0];
			return row?.users ?? null;
		},
		async updateUser({ id, image, ...userData }) {
			if (!id) throw new Error("User not found");
			await db.transaction(async (tx) => {
				await tx
					.update(users)
					.set({
						...userData,
						image: image as ImageUpload.ImageUrlOrKey | null,
					})
					.where(eq(users.id, User.UserId.make(id)));
				await enqueueLoopsSync(tx, User.UserId.make(id));
			});
			const rows = await db
				.select()
				.from(users)
				.where(eq(users.id, User.UserId.make(id)))
				.limit(1);
			const row = rows[0];
			if (!row) throw new Error("User not found");
			return row;
		},
		async deleteUser(userId) {
			await db.delete(users).where(eq(users.id, User.UserId.make(userId)));
		},
		async linkAccount(account: LinkAccountData) {
			if (account.provider === "workos") {
				const identity = options?.getSsoIdentity();
				if (!identity || identity.profileId !== account.providerAccountId) {
					throw new Error("The SSO identity has not been verified.");
				}
				await db.transaction(async (tx) => {
					await tx
						.select({ id: organizations.id })
						.from(organizations)
						.where(eq(organizations.id, identity.organizationId))
						.for("update");
					const [user] = await tx
						.select({ email: users.email })
						.from(users)
						.where(eq(users.id, User.UserId.make(account.userId)))
						.for("update");
					if (user?.email.toLowerCase() !== identity.email) {
						throw new Error("The SSO account belongs to a different user.");
					}
					const linked = await tx
						.selectDistinct({ userId: accounts.userId })
						.from(accounts)
						.where(
							and(
								eq(accounts.provider, "workos"),
								eq(accounts.providerAccountId, identity.profileId),
							),
						)
						.limit(2);
					if (linked.some((row) => row.userId !== account.userId)) {
						throw new Error(
							"The SSO identity is already linked to another account.",
						);
					}
					if (linked.length > 0) return;
					await tx.insert(accounts).values({
						id: createHash("sha256")
							.update(`workos:${identity.profileId}`)
							.digest("base64url")
							.slice(0, 15),
						userId: account.userId,
						type: account.type,
						provider: "workos",
						providerAccountId: identity.profileId,
					});
				});
				return;
			}
			await db.insert(accounts).values({
				id: User.UserId.make(nanoId()),
				userId: account.userId,
				type: account.type,
				provider: account.provider,
				providerAccountId: account.providerAccountId,
				access_token: account.access_token,
				expires_in: account.expires_in as number,
				id_token: account.id_token,
				refresh_token: account.refresh_token,
				refresh_token_expires_in: account.refresh_token_expires_in as number,
				scope: account.scope,
				token_type: account.token_type,
			});
		},
		async unlinkAccount({ providerAccountId, provider }: UnlinkAccountData) {
			await db
				.delete(accounts)
				.where(
					and(
						eq(accounts.providerAccountId, providerAccountId),
						eq(accounts.provider, provider),
					),
				);
		},
		async createSession(data) {
			await db.insert(sessions).values({
				id: nanoId(),
				expires: data.expires,
				sessionToken: data.sessionToken,
				userId: User.UserId.make(data.userId),
			});
			const rows = await db
				.select()
				.from(sessions)
				.where(eq(sessions.sessionToken, data.sessionToken))
				.limit(1);
			const row = rows[0];
			if (!row) throw new Error("User not found");
			return row;
		},
		async getSessionAndUser(sessionToken) {
			const rows = await db
				.select({
					user: users,
					session: {
						id: sessions.id,
						userId: sessions.userId,
						sessionToken: sessions.sessionToken,
						expires: sessions.expires,
					},
				})
				.from(sessions)
				.innerJoin(users, eq(users.id, sessions.userId))
				.where(eq(sessions.sessionToken, sessionToken))
				.limit(1);
			const row = rows[0];
			if (!row) return null;
			const { user, session } = row;
			return {
				user,
				session: {
					id: session.id,
					userId: User.UserId.make(session.userId),
					sessionToken: session.sessionToken,
					expires: session.expires,
				},
			};
		},
		async updateSession(session: UpdateSessionData) {
			const sessionUpdate: Partial<typeof sessions.$inferInsert> = {};
			if (session.expires) sessionUpdate.expires = session.expires;
			if (session.userId)
				sessionUpdate.userId = User.UserId.make(session.userId);

			if (Object.keys(sessionUpdate).length > 0) {
				await db
					.update(sessions)
					.set(sessionUpdate)
					.where(eq(sessions.sessionToken, session.sessionToken));
			}
			const rows = await db
				.select()
				.from(sessions)
				.where(eq(sessions.sessionToken, session.sessionToken))
				.limit(1);
			const row = rows[0];
			if (!row) throw new Error("Coding bug: updated session not found");
			return row;
		},
		async deleteSession(sessionToken) {
			await db.delete(sessions).where(eq(sessions.sessionToken, sessionToken));
		},
		async createVerificationToken(verificationToken) {
			const normalizedIdentifier =
				verificationToken.identifier?.toLowerCase() ?? "";
			const existingTokens = await db
				.select()
				.from(verificationTokens)
				.where(eq(verificationTokens.identifier, normalizedIdentifier))
				.limit(1);

			if (existingTokens.length > 0) {
				await db
					.update(verificationTokens)
					.set({
						token: verificationToken.token,
						expires: verificationToken.expires,
					})
					.where(eq(verificationTokens.identifier, normalizedIdentifier));

				return await db
					.select()
					.from(verificationTokens)
					.where(eq(verificationTokens.identifier, normalizedIdentifier))
					.limit(1)
					.then((rows) => rows[0]);
			}

			await db.insert(verificationTokens).values({
				expires: verificationToken.expires,
				identifier: normalizedIdentifier,
				token: verificationToken.token,
			});

			const rows = await db
				.select()
				.from(verificationTokens)
				.where(eq(verificationTokens.token, verificationToken.token))
				.limit(1);
			const row = rows[0];
			if (!row) throw new Error("Error: inserted verification token not found");
			return row;
		},
		async useVerificationToken({ identifier, token }) {
			const normalizedIdentifier = identifier?.toLowerCase() ?? "";
			const rows = await db
				.select()
				.from(verificationTokens)
				.where(eq(verificationTokens.identifier, normalizedIdentifier))
				.limit(1);
			const row = rows[0];
			if (!row) {
				console.warn("[useVerificationToken] No token found");
				return null;
			}
			// Claim the exact row we just read (identifier + token) with a single
			// delete, and only proceed if we actually removed it. This makes
			// consumption atomic: concurrent requests race on the same delete, so
			// at most one of them can claim the row, whether the guess is right or
			// wrong. Scoping by token too (not identifier alone) means the delete
			// can't clobber a resend that replaced this row after we read it.
			const result = await db
				.delete(verificationTokens)
				.where(
					and(
						eq(verificationTokens.identifier, row.identifier),
						eq(verificationTokens.token, row.token),
					),
				);
			if (getAffectedRows(result) !== 1) {
				console.warn("[useVerificationToken] Token already consumed");
				return null;
			}
			if (row.token !== token) {
				console.warn("[useVerificationToken] Token mismatch");
				return null;
			}
			return { ...row, identifier: normalizedIdentifier };
		},
	};
}