Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

Restrict sign-in to trycomp.ai, and never file a colleague as a lead

Lewis Carhartf737676c062e
diff --git a/apps/api/scripts/reenrich-contacts.ts b/apps/api/scripts/reenrich-contacts.ts
index 17577f26..f3cf336f 100644
--- a/apps/api/scripts/reenrich-contacts.ts
+++ b/apps/api/scripts/reenrich-contacts.ts
@@ -2,12 +2,12 @@ import { db } from "@crm/db";
import { ActivityStampService } from "../src/crm/activity-stamp.service";
import { EnrichmentLogService } from "../src/crm/enrichment-log.service";
import { AvatarService } from "../src/enrichment/avatar.service";
-import { LinkdapiClient } from "../src/enrichment/linkdapi.client";
import {
looksLikeSameCompany,
nameMatchesLocalPart,
searchTerms,
} from "../src/enrichment/contact-enrichment.service";
+import { LinkdapiClient } from "../src/enrichment/linkdapi.client";
/**
* Fills in every contact we can identify, once.
diff --git a/apps/api/src/google/google-match.service.ts b/apps/api/src/google/google-match.service.ts
index d5f520eb..69fd7a00 100644
--- a/apps/api/src/google/google-match.service.ts
+++ b/apps/api/src/google/google-match.service.ts
@@ -1,3 +1,4 @@
+import { WORKSPACE_DOMAINS } from "@crm/auth/workspace";
import { type Db, RecordSource } from "@crm/db";
import { Injectable, Logger } from "@nestjs/common";
import { EnrichmentLogService } from "../crm/enrichment-log.service";
@@ -98,7 +99,11 @@ export class GoogleMatchService {
const users = await this.db.user.findMany({ select: { email: true } });
const addresses = new Set<string>();
- const domains = new Set<string>();
+ // Seeded with the workspace domains rather than relying only on what the
+ // User table happens to contain. Sign-in is restricted to these, so they
+ // are internal by definition — and this holds on an empty database, and
+ // for colleagues who have never signed in and so are not users yet.
+ const domains = new Set<string>(WORKSPACE_DOMAINS);
for (const user of users) {
const email = user.email.toLowerCase();
diff --git a/apps/api/test/workspace.spec.ts b/apps/api/test/workspace.spec.ts
new file mode 100644
index 00000000..51a31604
--- /dev/null
+++ b/apps/api/test/workspace.spec.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "bun:test";
+import { isWorkspaceEmail } from "@crm/auth/workspace";
+import { externalParticipants } from "../src/google/participants";
+
+describe("isWorkspaceEmail", () => {
+ it("admits our people", () => {
+ for (const email of [
+ ]) {
+ expect(isWorkspaceEmail(email)).toBe(true);
+ }
+ });
+
+ it("refuses everybody else", () => {
+ for (const email of [
+ "",
+ null,
+ undefined,
+ ]) {
+ expect(isWorkspaceEmail(email)).toBe(false);
+ }
+ });
+
+ it("is not fooled by a lookalike domain", () => {
+ // The boundary is a dot, not a substring — otherwise anyone could
+ // register trycomp.ai.evil.com and walk into an internal CRM.
+ for (const email of [
+ ]) {
+ expect(isWorkspaceEmail(email)).toBe(false);
+ }
+ });
+});
+
+describe("internal addresses never become leads", () => {
+ // Empty sets: proves the workspace domain is excluded on its own, not
+ // because a colleague happens to be a CRM user yet.
+ const options = {
+ ourDomains: new Set(["trycomp.ai"]),
+ ourAddresses: new Set<string>(),
+ suppressedDomains: new Set<string>(),
+ };
+
+ it("drops colleagues even when they are not users", () => {
+ const result = externalParticipants(
+ [
+ { email: "[email protected]", name: "Lewis" },
+ { email: "[email protected]", name: "New Starter" },
+ { email: "[email protected]", name: "Jane" },
+ ],
+ options,
+ );
+
+ expect(result.map((person) => person.email)).toEqual(["[email protected]"]);
+ });
+
+ it("stores nothing for a wholly internal thread", () => {
+ // No external side means the sync drops the thread entirely — an internal
+ // conversation is never written to the CRM.
+ expect(
+ externalParticipants(
+ [
+ { email: "[email protected]", name: null },
+ { email: "[email protected]", name: null },
+ ],
+ options,
+ ),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/auth/package.json b/packages/auth/package.json
index 536e3da2..c36d51a6 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -6,7 +6,8 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client.ts",
- "./scopes": "./src/scopes.ts"
+ "./scopes": "./src/scopes.ts",
+ "./workspace": "./src/workspace.ts"
},
"scripts": {
"auth:generate": "better-auth generate --config src/auth.ts --output ../db/prisma/schema.prisma --y",
diff --git a/packages/auth/src/auth.ts b/packages/auth/src/auth.ts
index 37b36fcd..ccce7fac 100644
--- a/packages/auth/src/auth.ts
+++ b/packages/auth/src/auth.ts
@@ -1,8 +1,10 @@
import { db } from "@crm/db";
import { type BetterAuthOptions, betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
+import { APIError } from "better-auth/api";
import { env } from "./env";
import { SYNC_SCOPES } from "./scopes";
+import { isWorkspaceEmail, PRIMARY_WORKSPACE_DOMAIN } from "./workspace";
const socialProviders: NonNullable<BetterAuthOptions["socialProviders"]> = {};
@@ -32,6 +34,12 @@ if (env.google) {
// token. The missing-refresh-token case is detected and repaired rather
// than pre-empted.
accessType: "offline",
+
+ // Google only offers accounts on our domain in the chooser. This is a
+ // convenience, not the control — `hd` is a hint the client sends and a
+ // determined caller can omit it, so the real check is the database hook
+ // below, which sees the verified email.
+ hd: PRIMARY_WORKSPACE_DOMAIN,
};
}
@@ -81,7 +89,31 @@ export const auth = betterAuth({
trustedOrigins: [...env.trustedOrigins],
hooks: {},
- databaseHooks: {},
+
+ databaseHooks: {
+ user: {
+ create: {
+ /**
+ * The actual door.
+ *
+ * Runs against the profile Google verified, before a row exists, so
+ * a personal account that gets past the `hd` hint never becomes a
+ * user. This is a single-tenant internal tool: an account outside
+ * the workspace has nothing legitimate to do here, and every record
+ * is visible to every signed-in person.
+ */
+ before: async (user) => {
+ if (!isWorkspaceEmail(user.email)) {
+ throw new APIError("FORBIDDEN", {
+ message: `Comp AI CRM is internal. Sign in with your @${PRIMARY_WORKSPACE_DOMAIN} account.`,
+ });
+ }
+
+ return { data: user };
+ },
+ },
+ },
+ },
});
export type Auth = typeof auth;
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index ea661bcb..5c86829e 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -8,3 +8,8 @@ export {
REQUIRED_SCOPES,
SYNC_SCOPES,
} from "./scopes";
+export {
+ isWorkspaceEmail,
+ PRIMARY_WORKSPACE_DOMAIN,
+ WORKSPACE_DOMAINS,
+} from "./workspace";
diff --git a/packages/auth/src/workspace.ts b/packages/auth/src/workspace.ts
new file mode 100644
index 00000000..6da72f4c
--- /dev/null
+++ b/packages/auth/src/workspace.ts
@@ -0,0 +1,38 @@
+/**
+ * Who is allowed in, and who counts as "us".
+ *
+ * One list, used by two things that must never disagree: the sign-in guard, and
+ * the sync's decision about which side of a conversation is external. If they
+ * drifted, a colleague's address would either be refused at the door or filed
+ * as a sales lead.
+ */
+
+/** Domains whose Google accounts may sign in. */
+export const WORKSPACE_DOMAINS = ["trycomp.ai"] as const;
+
+/** The one Google shows in its account chooser. */
+export const PRIMARY_WORKSPACE_DOMAIN = WORKSPACE_DOMAINS[0];
+
+/**
+ * Whether an address belongs to us.
+ *
+ * Subdomain-aware, so `[email protected]` counts, but a lookalike like
+ * `trycomp.ai.evil.com` does not — the boundary is a dot, not a substring.
+ */
+export function isWorkspaceEmail(email: string | null | undefined): boolean {
+ const value = email?.trim().toLowerCase();
+ if (!value) return false;
+
+ // Exactly one `@`. Reading the *last* one would let `[email protected]@trycomp.ai`
+ // look like it belongs to us. Google never issues an address like that, but
+ // a door should not depend on the other side being well behaved.
+ const parts = value.split("@");
+ if (parts.length !== 2) return false;
+
+ const [local, host] = parts;
+ if (!local || !host) return false;
+
+ return WORKSPACE_DOMAINS.some(
+ (domain) => host === domain || host.endsWith(`.${domain}`),
+ );
+}