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
46 changes: 34 additions & 12 deletions lib/github/install-audience.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ import {
openPullRequest,
putFile,
} from "./repos";
import { findInstallCandidates, previewInstallAtPath } from "./install-tracker";
import {
findInstallCandidates,
hasTrackerReference,
previewInstallAtPath,
} from "./install-tracker";

const SITE_ORIGIN = env.siteUrl.replace(/\/$/, "");
const BRANCH_PREFIX = "crawlproof/audience-hub";
Expand Down Expand Up @@ -284,30 +288,48 @@ export async function installAudienceHub(
repo: input.repo,
rootPath: input.rootPath,
});

// Pass 1: if ANY candidate file already references stats.js, the
// tracker is installed — even when it lives in a lower-ranked file or
// is formatted across multiple lines. Never add a duplicate tag.
const contents = new Map<string, { sha: string; content: string }>();
for (const candidate of candidates) {
const preview = await previewInstallAtPath({
const file = await getFileContent({
token: input.token,
owner: input.owner,
repo: input.repo,
path: candidate.path,
projectId: input.projectId,
ref: base,
});
if (preview.status === "already_installed") {
trackerAlready = preview.path;
if (!file) continue;
contents.set(file.path, { sha: file.sha, content: file.content });
if (hasTrackerReference(file.content)) {
trackerAlready = file.path;
break;
}
if (preview.status === "ready") {
const file = await getFileContent({
}

// Pass 2: only when no candidate has it do we inject into the best one.
if (!trackerAlready) {
for (const candidate of candidates) {
const preview = await previewInstallAtPath({
token: input.token,
owner: input.owner,
repo: input.repo,
path: preview.path,
ref: base,
path: candidate.path,
projectId: input.projectId,
});
if (file) {
trackerEdit = { path: file.path, sha: file.sha, after: preview.after };
if (preview.status === "already_installed") {
trackerAlready = preview.path;
break;
}
if (preview.status === "ready") {
const file = contents.get(preview.path);
if (file) {
trackerEdit = { path: preview.path, sha: file.sha, after: preview.after };
}
break;
}
break;
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions lib/github/install-tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,17 @@ function injectBeforeBodyClose(
return updated;
}

/**
* Loose duplicate guard: does this file reference our stats.js at all?
* The line-based regex below only matches single-line tags, so a
* prettier-formatted multi-line <Script ... /> slips past it and we'd
* inject a second copy. Any reference to the tracker origin's /stats.js
* means "already installed" for injection purposes.
*/
export function hasTrackerReference(content: string): boolean {
return content.includes(`${TRACKER_ORIGIN}/stats.js`);
}

function trackerTagLineRe() {
const origin = escapeRegExp(TRACKER_ORIGIN);
return new RegExp(
Expand Down Expand Up @@ -395,6 +406,11 @@ export async function previewInstallAtPath(input: {
if (normalized) {
return { status: "already_installed", path: file.path };
}
// Multi-line or unusually formatted tags won't match the line regex but
// are still an install — never inject a duplicate next to one.
if (hasTrackerReference(file.content)) {
return { status: "already_installed", path: file.path };
}
if (!/<\/body>/i.test(file.content)) {
return {
status: "not_a_template",
Expand Down Expand Up @@ -593,6 +609,11 @@ export async function installTracker(input: InstallInput): Promise<InstallResult
if (normalized) {
return { kind: "already", path: file.path };
}
// Same guard as previewInstallAtPath: a multi-line tag the line regex
// can't parse still counts as installed.
if (hasTrackerReference(file.content)) {
return { kind: "already", path: file.path };
}
if (/<\/body>/i.test(file.content)) {
return { kind: "hit", file };
}
Expand Down
31 changes: 31 additions & 0 deletions tests/audience-hub.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
generatedClientHelper,
serverHelperPath,
} from "@/lib/github/install-audience";
import { hasTrackerReference } from "@/lib/github/install-tracker";

describe("statusForEvent", () => {
it("maps lifecycle events to lifecycle statuses", () => {
Expand Down Expand Up @@ -123,6 +124,36 @@ describe("generated files", () => {
});
});

describe("hasTrackerReference (duplicate-install guard)", () => {
// env.siteUrl is stubbed to http://localhost:3000 in tests/setup.ts.
const origin = "http://localhost:3000";

it("detects a single-line script tag", () => {
expect(
hasTrackerReference(
`<body><script data-site="abc" src="${origin}/stats.js" async></script></body>`,
),
).toBe(true);
});

it("detects a prettier-formatted multi-line <Script /> tag", () => {
const layout = ` <Script
data-site="11111111-2222-3333-4444-555555555555"
src="${origin}/stats.js"
strategy="afterInteractive"
/>
</body>`;
expect(hasTrackerReference(layout)).toBe(true);
});

it("ignores files without the tracker", () => {
expect(hasTrackerReference("<body><h1>hi</h1></body>")).toBe(false);
expect(
hasTrackerReference('<script src="https://other-analytics.example/stats.js">'),
).toBe(false);
});
});

describe("project ingest keys", () => {
it("mints cpk_ keys and verifies by peppered sha256", async () => {
const { mintProjectKey, hashProjectKey, isProjectKeyShape } = await import(
Expand Down
Loading