Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions apps/claim-db-worker/__tests__/auth-url-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { NextRequest } from "next/server";
import { POST } from "../app/api/auth/url/route";
import { claimCampaign } from "../lib/claim-campaign";

const authUrlFor = async (body: unknown) => {
const response = await POST(
new NextRequest("http://localhost:3000/api/auth/url", {
method: "POST",
body: JSON.stringify(body),
})
);
const { authUrl } = (await response.json()) as { authUrl: string };
return new URL(authUrl);
};

describe("auth url API", () => {
const originalClientId = process.env.CLIENT_ID;
beforeEach(() => {
process.env.CLIENT_ID = "client-1";
});
afterEach(() => {
process.env.CLIENT_ID = originalClientId;
});

it("passes the CLI's command, medium and output mode on to sign-in", async () => {
const url = await authUrlFor({
redirectUri: "http://localhost:3000/api/auth/callback?projectID=p",
utm: { utm_source: "create-pg", utm_medium: "cli", utm_content: "json" },
});
expect(url.origin).toBe("https://auth.prisma.io");
expect(url.searchParams.get("utm_source")).toBe("create-pg");
expect(url.searchParams.get("utm_medium")).toBe("cli");
expect(url.searchParams.get("utm_content")).toBe("json");
});

it("never passes a custom user agent or env-file value on", async () => {
const url = await authUrlFor({
redirectUri: "http://localhost:3000/api/auth/callback?projectID=p",
utm: { utm_source: "Jane Doe/acme-secret-app", utm_medium: "cli" },
});
expect(url.searchParams.get("utm_source")).toBe("create-db");
expect(url.search).not.toMatch(/jane|acme/i);
});

it("keeps the old tags for a page without the CLI's", async () => {
const url = await authUrlFor({
redirectUri: "http://localhost:3000/api/auth/callback?projectID=p",
});
expect(url.searchParams.get("utm_source")).toBe("create-db-frontend");
expect(url.searchParams.get("utm_medium")).toBe("claim_button");
expect(url.searchParams.has("utm_content")).toBe(false);
});
});

describe("claimCampaign", () => {
it.each([
[{ utm_source: "create-db", utm_medium: "cli" }, { utm_source: "create-db", utm_medium: "cli" }],
[{ utm_source: " Create-Postgres ", utm_medium: "CLI", utm_content: "quiet" }, { utm_source: "create-postgres", utm_medium: "cli", utm_content: "quiet" }],
[{ utm_source: "create-db-frontend", utm_medium: "claim_button" }, { utm_source: "create-db-frontend", utm_medium: "claim_button" }],
[{ utm_source: "claude-code/my-app", utm_medium: "cli" }, { utm_source: "create-db", utm_medium: "cli" }],
[{ utm_source: "x", utm_medium: "email", utm_content: "free text" }, { utm_source: "create-db-frontend", utm_medium: "claim_button" }],
[null, { utm_source: "create-db-frontend", utm_medium: "claim_button" }],
["not an object", { utm_source: "create-db-frontend", utm_medium: "claim_button" }],
])("normalises %j", (input, expected) => {
expect(claimCampaign(input)).toEqual(expected);
});
});
28 changes: 28 additions & 0 deletions apps/claim-db-worker/__tests__/claim.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,34 @@ describe("claim page", () => {
expect(claimButton).toBeDisabled();
});

it("sends the CLI's tags on this page to the auth URL route", async () => {
mockSearchParams.set("projectID", "test-project-123");
mockSearchParams.set("utm_source", "create-pg");
mockSearchParams.set("utm_medium", "cli");
mockSearchParams.set("utm_content", "json");
render(<ClaimPage />);

fireEvent.click(screen.getByRole("button", { name: "Claim database" }));

await waitFor(() => {
expect(mockFetch).toHaveBeenCalledWith(
"/api/auth/url",
expect.objectContaining({ method: "POST" })
);
});
const body = JSON.parse(
(mockFetch.mock.calls[0]![1] as { body: string }).body
);
expect(body.utm).toEqual({
utm_source: "create-pg",
utm_medium: "cli",
utm_content: "json",
});
mockSearchParams.delete("utm_source");
mockSearchParams.delete("utm_medium");
mockSearchParams.delete("utm_content");
});

it("starts one claim however often the button is clicked", async () => {
mockSearchParams.set("projectID", "test-project-123");
render(<ClaimPage />);
Expand Down
10 changes: 7 additions & 3 deletions apps/claim-db-worker/app/api/auth/url/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import { claimCampaign } from "@/lib/claim-campaign";

export async function POST(request: NextRequest) {
const body: { redirectUri: string } = await request.json();
const body: { redirectUri: string; utm?: unknown } = await request.json();
const redirectUri = body.redirectUri;
const clientId = process.env.CLIENT_ID;

Expand All @@ -18,8 +19,11 @@ export async function POST(request: NextRequest) {
searchParams.set("response_type", "code");
searchParams.set("scope", "workspace:admin");
searchParams.set("state", generateState());
searchParams.set("utm_source", "create-db-frontend");
searchParams.set("utm_medium", "claim_button");
// The claim page's own tags, from the CLI that made the database. Only
// known command names pass; see `claimCampaign`.
for (const [key, value] of Object.entries(claimCampaign(body.utm))) {
if (value) searchParams.set(key, value);
}

const authUrl = `https://auth.prisma.io/authorize?${searchParams.toString()}`;

Expand Down
10 changes: 9 additions & 1 deletion apps/claim-db-worker/app/claim/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,15 @@ function ClaimContent() {
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ redirectUri: redirectUri.toString() }),
body: JSON.stringify({
redirectUri: redirectUri.toString(),
// The CLI's tags on this page's URL; the server keeps known values only.
utm: {
utm_source: searchParams.get("utm_source") ?? undefined,
utm_medium: searchParams.get("utm_medium") ?? undefined,
utm_content: searchParams.get("utm_content") ?? undefined,
},
}),
});

if (!response.ok) {
Expand Down
65 changes: 65 additions & 0 deletions apps/claim-db-worker/lib/claim-campaign.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Campaign tags for the sign-in link the claim button opens.
*
* The CLI tags the claim URL with the command that made the database
* (`utm_source=create-db`, `create-pg` or `create-postgres`), `utm_medium=cli`
* and the output mode (`utm_content`). Passing those on to sign-in lets a
* signup be credited to the command instead of the generic claim button.
*
* The CLI's `utm_source` can also be a free-text value: the hidden
* `--user-agent` flag, or `PRISMA_ACTOR_NAME/PRISMA_ACTOR_PROJECT` from the
* user's env file, which can name a person or a project. Only known values
* are passed on; anything else is replaced, so no value from a user's
* environment reaches the signup.
*/

export type ClaimCampaign = {
utm_source: string;
utm_medium: string;
utm_content?: string;
};

const KNOWN_SOURCES = new Set([
"create-db",
"create-pg",
"create-postgres",
"create-db-frontend",
"create_db_web",
]);
const KNOWN_MEDIUMS = new Set(["cli", "claim_button"]);
const KNOWN_CONTENT = new Set(["default", "json", "env", "quiet"]);

/** The tags the claim button used before it passed the CLI's on. */
export const DEFAULT_CLAIM_CAMPAIGN: ClaimCampaign = {
utm_source: "create-db-frontend",
utm_medium: "claim_button",
};

function normalize(value: unknown): string {
return typeof value === "string" ? value.trim().toLowerCase() : "";
}

export function claimCampaign(input: unknown): ClaimCampaign {
const tags =
input && typeof input === "object" ? (input as Record<string, unknown>) : {};
const source = normalize(tags.utm_source);
const medium = normalize(tags.utm_medium);
const content = normalize(tags.utm_content);

const utmMedium = KNOWN_MEDIUMS.has(medium)
? medium
: DEFAULT_CLAIM_CAMPAIGN.utm_medium;
const utmSource = KNOWN_SOURCES.has(source)
? source
: // A CLI claim whose tag was a custom user agent: keep that it came from
// the CLI, drop the custom value.
utmMedium === "cli"
? "create-db"
: DEFAULT_CLAIM_CAMPAIGN.utm_source;

return {
utm_source: utmSource,
utm_medium: utmMedium,
...(KNOWN_CONTENT.has(content) && { utm_content: content }),
};
}
Loading