Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
fix(api): add one-click local session login (#249)
grim5699b1c80bae
diff --git a/README.md b/README.mdindex 88a9fade..1fc750a2 100644--- a/README.md+++ b/README.md@@ -353,13 +353,14 @@ short version:| `bun run db:seed` | Top up the demo pipeline (idempotent) || `bun run db:studio` | Prisma Studio || `bun run --filter=api trpc:generate` | Regenerate the `AppRouter` type |-| `bun run --filter=api dev:session` | Print a session cookie for a local user |+| `bun run --filter=api dev:session` | Print a one-click local sign-in link |Scope any of them with a Turborepo filter: `bun run dev --filter=api`.-Because sign-in goes through an identity provider, there is no way to get a session from a terminal —-`dev:session` writes the rows Better Auth would have written and prints the cookie it-would have set. It refuses to run with `NODE_ENV=production`.+Because sign-in goes through an identity provider, there is no way to get a session from a terminal.+`dev:session` writes the rows Better Auth would have written and prints a one-click browser link.+The link sets the local session cookie and opens the app. It refuses to run with+`NODE_ENV=production`.## Deployingdiff --git a/apps/api/scripts/dev-session-config.ts b/apps/api/scripts/dev-session-config.tsnew file mode 100644index 00000000..e807a91a--- /dev/null+++ b/apps/api/scripts/dev-session-config.ts@@ -0,0 +1,6 @@+const MINUTE_MS = 60_000;++export const DEV_SESSION = {+ cookie: { days: 7, maxAgeSeconds: 7 * 24 * 60 * 60 },+ login: { timeoutMs: 10 * MINUTE_MS },+} as const;diff --git a/apps/api/scripts/dev-session-http.ts b/apps/api/scripts/dev-session-http.tsnew file mode 100644index 00000000..92b75245--- /dev/null+++ b/apps/api/scripts/dev-session-http.ts@@ -0,0 +1,45 @@+import { DEV_SESSION } from "./dev-session-config";++type DevSessionResponseInput = {+ appUrl: URL;+ cookieName: string;+ cookieValue: string;+};++export function localAppUrl(value?: string): URL {+ const origin = value+ ?.split(",")+ .map((candidate) => candidate.trim())+ .find(Boolean);+ return new URL(origin ?? "http://localhost:3000");+}++export function localLoginHost(appUrl: URL): string {+ if (appUrl.hostname === "localhost" || appUrl.hostname === "127.0.0.1") {+ return appUrl.hostname;+ }++ throw new Error("APP_URL must use localhost or 127.0.0.1 for dev:session.");+}++export function createDevSessionResponse({+ appUrl,+ cookieName,+ cookieValue,+}: DevSessionResponseInput): Response {+ const cookie = [+ `${cookieName}=${cookieValue}`,+ "Path=/",+ "HttpOnly",+ "SameSite=Lax",+ `Max-Age=${DEV_SESSION.cookie.maxAgeSeconds}`,+ ].join("; ");++ return new Response(null, {+ status: 302,+ headers: {+ location: appUrl.toString(),+ "set-cookie": cookie,+ },+ });+}diff --git a/apps/api/scripts/dev-session.ts b/apps/api/scripts/dev-session.tsindex 8df9b3dd..4bfa0fe7 100644--- a/apps/api/scripts/dev-session.ts+++ b/apps/api/scripts/dev-session.ts@@ -1,8 +1,14 @@import { AUTH_COOKIE_PREFIX } from "@crm/auth/cookies";+import { ensureWorkspaceMembership } from "@crm/auth/organization";import { db } from "@crm/db";+import { DEV_SESSION } from "./dev-session-config";+import {+ createDevSessionResponse,+ localAppUrl,+ localLoginHost,+} from "./dev-session-http";const COOKIE_NAME = `${AUTH_COOKIE_PREFIX}.session_token`;-const SESSION_DAYS = 7;if (process.env.NODE_ENV === "production") {throw new Error(@@ -17,6 +23,8 @@ if (!secret) {const email = process.argv[2] ?? "dev@localhost";const name = email.split("@")[0] ?? "Developer";+const appUrl = localAppUrl(process.env.APP_URL);+const loginHost = localLoginHost(appUrl);async function signCookieValue(value: string): Promise<string> {const key = await crypto.subtle.importKey(@@ -47,8 +55,15 @@ const user = await db.user.upsert({update: {},});+const workspaceId = await ensureWorkspaceMembership(user.id);+if (!workspaceId) {+ throw new Error("Could not enrol the development user in the workspace.");+}+const token = `dev-session-${user.id}`;-const expiresAt = new Date(Date.now() + SESSION_DAYS * 24 * 60 * 60 * 1000);+const expiresAt = new Date(+ Date.now() + DEV_SESSION.cookie.days * 24 * 60 * 60 * 1000,+);await db.session.upsert({where: { token },@@ -58,10 +73,48 @@ await db.session.upsert({userId: user.id,expiresAt,updatedAt: new Date(),+ activeOrganizationId: workspaceId,},- update: { expiresAt },+ update: { expiresAt, activeOrganizationId: workspaceId },});-console.log(`${COOKIE_NAME}=${await signCookieValue(token)}`);+const cookieValue = await signCookieValue(token);+const loginPath = `/login/${crypto.randomUUID()}`;++await new Promise<void>((resolve) => {+ let finished = false;+ let server: ReturnType<typeof Bun.serve>;+ let timeout: ReturnType<typeof setTimeout> | undefined;++ const finish = () => {+ if (finished) return;+ finished = true;+ if (timeout) clearTimeout(timeout);+ server.stop();+ resolve();+ };++ server = Bun.serve({+ hostname: loginHost,+ port: 0,+ fetch(request) {+ if (new URL(request.url).pathname !== loginPath) {+ return new Response("Not found", { status: 404 });+ }++ setTimeout(finish, 0);+ return createDevSessionResponse({+ appUrl,+ cookieName: COOKIE_NAME,+ cookieValue,+ });+ },+ });++ timeout = setTimeout(finish, DEV_SESSION.login.timeoutMs);+ console.log("Open this link to sign in:");+ console.log(`http://${loginHost}:${server.port}${loginPath}`);+ console.log("The link expires in 10 minutes.");+});await db.$disconnect();diff --git a/apps/api/test/dev-session-http.spec.ts b/apps/api/test/dev-session-http.spec.tsnew file mode 100644index 00000000..d5f2aad3--- /dev/null+++ b/apps/api/test/dev-session-http.spec.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "bun:test";+import {+ createDevSessionResponse,+ localAppUrl,+ localLoginHost,+} from "../scripts/dev-session-http";++describe("dev session browser login", () => {+ it("sets the session cookie and redirects to the local app", () => {+ const response = createDevSessionResponse({+ appUrl: new URL("http://localhost:3000/tripwire"),+ cookieName: "crm.session_token",+ cookieValue: "signed%3D",+ });++ expect(response.status).toBe(302);+ expect(response.headers.get("location")).toBe(+ "http://localhost:3000/tripwire",+ );+ expect(response.headers.get("set-cookie")).toBe(+ "crm.session_token=signed%3D; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800",+ );+ });++ it("uses the application loopback host for the login link", () => {+ expect(localLoginHost(new URL("http://127.0.0.1:3000"))).toBe("127.0.0.1");+ expect(localLoginHost(new URL("http://localhost:3000"))).toBe("localhost");+ });++ it("uses the first configured application origin", () => {+ expect(+ localAppUrl("http://localhost:3000,http://127.0.0.1:3000").toString(),+ ).toBe("http://localhost:3000/");+ });++ it("refuses a non-local application URL", () => {+ expect(() => localLoginHost(new URL("https://crm.example.com"))).toThrow(+ "APP_URL must use localhost or 127.0.0.1 for dev:session.",+ );+ });+});