@analitikisler/ai-tag-debugger 0.6.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +15 -0
- package/README.tr.md +15 -0
- package/package.json +1 -1
- package/src/agent.js +29 -6
- package/src/audit.js +10 -2
- package/src/browser.js +74 -1
- package/src/cli.js +28 -0
- package/src/parsers.js +9 -4
- package/src/replay.js +97 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0 (2026-10-12)
|
|
4
|
+
|
|
5
|
+
Fixes from the first audit run across 18 real shops.
|
|
6
|
+
|
|
7
|
+
- **GA4 hits with a `gaf` parameter were missed and sent to the real GA4 property** (since 0.6.2). Some sites send `gaf=2` on every normal hit, so `view_item`, `add_to_cart` and others were reported as missing, and the test visits reached the site's analytics. Only copies to `www.google.com` and `doubleclick.net` are now left out, whatever their parameters, and every GA4 request is answered locally again.
|
|
8
|
+
- More Google tag pings are answered locally instead of reaching the real accounts: Google Ads remarketing (`www.google.com/rmkt/collect`), Merchant Center (`merchant-center-analytics.goog/mc/collect`), the Google tag's `/g/s/collect`, and consent mode pings on any host, including Google tag gateway paths on the site's own domain (`/<id>/gs/ccm/collect`).
|
|
9
|
+
- One browsing step can no longer stall a run: a model call that doesn't answer within 3 minutes, or a browser action that doesn't finish within 2, ends the journey as incomplete with a note.
|
|
10
|
+
- **Saved sites and `replay`.** `run --save-site <dir>` also saves every response the site sent (as a Playwright HAR file per journey and viewport, without tracking requests, cookies sent or set, authorization headers, form bodies, or requests with user data in their address) and the steps taken. `replay <dir>...` audits those pages again offline, with no network and no AI model, and lists findings that are new or gone. It exits with code 1 when any changed; `--update` makes the new findings the expected ones. Steps the AI took by ref are saved as CSS paths, or as visible text inside iframes. Images, fonts and video are left out of the recording; when the browser closed early, there is no recording to clean instead of an error.
|
|
11
|
+
|
|
3
12
|
## 0.6.3 (2026-10-12)
|
|
4
13
|
|
|
5
14
|
- The audited site's own email address in a `mailto:` link or a link field (`link_url`, `link_text`, `gtm.elementUrl`, `gtm.elementText`), such as the contact link in a GTM `gtm.linkClick` push, is no longer reported as unhashed user data or redacted. An own-domain address anywhere else, and every named user data field (`email`, `user_data`, `em`, …), is still redacted and reported.
|
package/README.md
CHANGED
|
@@ -169,6 +169,19 @@ Each browsing step is one model call, so usage grows with **journeys × viewport
|
|
|
169
169
|
- **Replay without AI.** After one AI run, copy the steps into `journeys[].steps` and use `--scripted` (with `--no-ai` for zero model calls) on every deploy.
|
|
170
170
|
- **Use a chat app.** Over MCP, the chat app's own model does the browsing, so no API key is used at all.
|
|
171
171
|
|
|
172
|
+
### Check a new version against saved sites
|
|
173
|
+
|
|
174
|
+
`--save-site <dir>` also saves every response the site sent and the steps taken. `replay` then audits the same pages again offline, with no network and no AI model, so it costs nothing. It lists findings that are new or gone compared with the saved run:
|
|
175
|
+
|
|
176
|
+
```bash
|
|
177
|
+
npx @analitikisler/ai-tag-debugger run --site https://www.yourshop.com --journey purchase --save-site saved/yourshop
|
|
178
|
+
npx @analitikisler/ai-tag-debugger replay saved/*
|
|
179
|
+
✗ https://www.yourshop.com (saved/yourshop): 0 new, 1 gone
|
|
180
|
+
- warning duplicate purchase desktop ga4 page_view
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
The first run's findings become the expected ones. When a change is right, for example a false alarm that is fixed, `replay --update` makes the new findings the expected ones. Use it to check a new version of the tool against sites you know, or a site change against its last good run. A saved site is usually a few MB. It leaves out tracking requests, images and video, cookies, authorization headers, form data, and requests with an email or other user data in their address. It still holds the site's pages and scripts, so keep sites you don't own out of public repositories.
|
|
184
|
+
|
|
172
185
|
## Configure your site
|
|
173
186
|
|
|
174
187
|
`ai-tag-debugger.config.json`:
|
|
@@ -229,6 +242,8 @@ ai-tag-debugger run [--site <url>] [--config <file>] [--journey <id>] [--goal "<
|
|
|
229
242
|
[--max-steps <n>] [--out <dir>] [--viewport desktop|mobile] [--providers <list>]
|
|
230
243
|
[--provider anthropic|openai|gemini|openai-compatible] [--model <id>] [--base-url <url>]
|
|
231
244
|
[--lang en|tr] [--allow-host <host>] [--keep-bodies] [--scripted] [--no-ai] [--fail-on broken|risk|warning|never] [--headed]
|
|
245
|
+
[--save-site <dir>]
|
|
246
|
+
ai-tag-debugger replay <dir>... [--update] [--out <dir>]
|
|
232
247
|
ai-tag-debugger mcp [--http] [--port <n>] [--host <addr>] [--token <secret>] [--public-url <https url>] [--reports <dir>]
|
|
233
248
|
[--allow-private-network]
|
|
234
249
|
```
|
package/README.tr.md
CHANGED
|
@@ -171,6 +171,19 @@ Her gezinme adımı bir model çağrısıdır. Yani kullanım **senaryo × ekran
|
|
|
171
171
|
- **Yapay zekâ olmadan tekrar oynatın.** Bir yapay zekâ çalıştırmasından sonra adımları `journeys[].steps` içine kopyalayın ve her deploy'da `--scripted` (hiç model çağrısı olmaması için `--no-ai` ile birlikte) kullanın.
|
|
172
172
|
- **Bir yapay zekâ asistanı kullanın.** MCP üzerinden gezinmeyi asistanın kendi modeli yapar, hiç API anahtarı kullanılmaz.
|
|
173
173
|
|
|
174
|
+
### Yeni bir sürümü kaydedilmiş sitelerle karşılaştırın
|
|
175
|
+
|
|
176
|
+
`--save-site <klasör>`, sitenin gönderdiği her yanıtı ve atılan adımları da kaydeder. `replay` aynı sayfaları ağ ve yapay zekâ modeli olmadan, çevrimdışı olarak yeniden denetler; bu yüzden hiçbir maliyeti yoktur. Kaydedilen çalıştırmaya göre yeni çıkan ya da kaybolan bulguları listeler:
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
npx @analitikisler/ai-tag-debugger run --site https://www.magazaniz.com --journey purchase --save-site saved/magazaniz
|
|
180
|
+
npx @analitikisler/ai-tag-debugger replay saved/*
|
|
181
|
+
✗ https://www.magazaniz.com (saved/magazaniz): 0 new, 1 gone
|
|
182
|
+
- warning duplicate purchase desktop ga4 page_view
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
İlk çalıştırmanın bulguları beklenen bulgular olur. Bir değişiklik doğruysa (örneğin düzeltilmiş bir yanlış alarm), `replay --update` yeni bulguları beklenen bulgular yapar. Aracın yeni bir sürümünü bildiğiniz sitelerle ya da bir site değişikliğini son sağlıklı çalıştırmayla karşılaştırmak için kullanın. Kaydedilmiş bir site genellikle birkaç MB'tır. İzleme isteklerini, görselleri ve videoları, çerezleri, yetkilendirme başlıklarını, form verilerini ve adresinde e-posta ya da başka kullanıcı verisi olan istekleri içermez. Yine de sitenin sayfalarını ve betiklerini içerdiği için size ait olmayan siteleri herkese açık depolara koymayın.
|
|
186
|
+
|
|
174
187
|
## Sitenizi ayarlayın
|
|
175
188
|
|
|
176
189
|
`ai-tag-debugger.config.json`:
|
|
@@ -231,6 +244,8 @@ ai-tag-debugger run [--site <url>] [--config <file>] [--journey <id>] [--goal "<
|
|
|
231
244
|
[--max-steps <n>] [--out <dir>] [--viewport desktop|mobile] [--providers <list>]
|
|
232
245
|
[--provider anthropic|openai|gemini|openai-compatible] [--model <id>] [--base-url <url>]
|
|
233
246
|
[--lang en|tr] [--allow-host <host>] [--keep-bodies] [--scripted] [--no-ai] [--fail-on broken|risk|warning|never] [--headed]
|
|
247
|
+
[--save-site <dir>]
|
|
248
|
+
ai-tag-debugger replay <dir>... [--update] [--out <dir>]
|
|
234
249
|
ai-tag-debugger mcp [--http] [--port <n>] [--host <addr>] [--token <secret>] [--public-url <https url>] [--reports <dir>]
|
|
235
250
|
[--allow-private-network]
|
|
236
251
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@analitikisler/ai-tag-debugger",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Open-source AI agent that QA-tests your website's analytics, ad and consent tracking (GA4, GTM, Google Ads, Meta, TikTok). Bring your own model (Claude, OpenAI, Gemini) or use it from your chat app over MCP.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/agent.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import path from "node:path";
|
|
1
2
|
import { AuditSession } from "./browser.js";
|
|
2
3
|
import { messages } from "./i18n.js";
|
|
3
4
|
import { createProvider, PROVIDERS } from "./providers.js";
|
|
@@ -87,6 +88,19 @@ export function validateAction(input) {
|
|
|
87
88
|
return null;
|
|
88
89
|
}
|
|
89
90
|
|
|
91
|
+
// One hung page or model request must not stall a whole run.
|
|
92
|
+
const MODEL_TIMEOUT_MS = 180_000;
|
|
93
|
+
const ACTION_TIMEOUT_MS = 120_000;
|
|
94
|
+
|
|
95
|
+
class StepTimeout extends Error {}
|
|
96
|
+
|
|
97
|
+
/** The promise's value, or a StepTimeout with this message once ms have passed. */
|
|
98
|
+
function withTimeout(promise, ms, message) {
|
|
99
|
+
let timer;
|
|
100
|
+
const timeout = new Promise((_, reject) => (timer = setTimeout(() => reject(new StepTimeout(message)), ms)));
|
|
101
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
102
|
+
}
|
|
103
|
+
|
|
90
104
|
/**
|
|
91
105
|
* Lets the AI model drive the browser through one journey.
|
|
92
106
|
* @param {AuditSession} session
|
|
@@ -106,7 +120,7 @@ export async function runAgentJourney(session, journey, opts = {}) {
|
|
|
106
120
|
});
|
|
107
121
|
|
|
108
122
|
for (let turn = 0; turn < maxSteps; turn++) {
|
|
109
|
-
const { toolCalls, stop } = await chat.next();
|
|
123
|
+
const { toolCalls, stop } = await withTimeout(chat.next(), MODEL_TIMEOUT_MS, "The model did not answer within 3 minutes.");
|
|
110
124
|
if (stop === "refusal") return { completed: false, note: "The model declined to continue this journey." };
|
|
111
125
|
if (toolCalls.length === 0) {
|
|
112
126
|
if (stop === "max_tokens") return { completed: false, note: "The model response was cut off." };
|
|
@@ -132,7 +146,7 @@ export async function runAgentJourney(session, journey, opts = {}) {
|
|
|
132
146
|
continue;
|
|
133
147
|
}
|
|
134
148
|
log(` ${call.input.reason}`);
|
|
135
|
-
const error = await session.act(call.input);
|
|
149
|
+
const error = await withTimeout(session.act(call.input), ACTION_TIMEOUT_MS, "The browser action did not finish within 2 minutes.");
|
|
136
150
|
results.push({ id: call.id, content: pageView(await session.snapshot(), error) });
|
|
137
151
|
}
|
|
138
152
|
if (finished) return finished;
|
|
@@ -153,20 +167,29 @@ export async function runScriptedJourney(session, journey, opts = {}) {
|
|
|
153
167
|
return { completed: true, note: "All scripted steps completed." };
|
|
154
168
|
}
|
|
155
169
|
|
|
170
|
+
/** The file a saved site keeps one journey's recorded responses in. */
|
|
171
|
+
export const harName = (journeyId, viewport) => `${String(journeyId).replace(/[^\w.-]+/g, "_")}-${viewport}.har`;
|
|
172
|
+
|
|
156
173
|
/**
|
|
157
174
|
* Runs one journey on one viewport and returns everything the checks need.
|
|
175
|
+
* opts.saveSite records the site's responses into that folder; opts.replaySite answers from one.
|
|
158
176
|
*/
|
|
159
177
|
export async function runJourney(config, journey, viewport, opts = {}) {
|
|
160
|
-
const
|
|
178
|
+
const har = (dir) => (dir ? path.join(dir, harName(journey.id, viewport)) : undefined);
|
|
179
|
+
const session = new AuditSession({
|
|
180
|
+
viewport, site: config.site, allowedHosts: config.allowed_hosts, providers: config.providers, keepBodies: config.keep_bodies === true,
|
|
181
|
+
blockHits: config.block_hits !== false, headless: !opts.headed, recordHar: har(opts.saveSite), replayHar: har(opts.replaySite),
|
|
182
|
+
});
|
|
161
183
|
try {
|
|
162
184
|
await session.start();
|
|
163
185
|
const startUrl = new URL(journey.start ?? "/", config.site).href;
|
|
164
186
|
const startError = await session.act({ action: "goto", url: startUrl, reason: `Open ${startUrl}` });
|
|
165
187
|
if (startError) return { ...collect(session, journey, viewport), completed: false, note: `Could not open the start page: ${startError}` };
|
|
166
188
|
|
|
167
|
-
const outcome = opts.scripted
|
|
168
|
-
|
|
169
|
-
|
|
189
|
+
const outcome = await (opts.scripted ? runScriptedJourney(session, journey, opts) : runAgentJourney(session, journey, opts)).catch((err) => {
|
|
190
|
+
if (err instanceof StepTimeout) return { completed: false, note: err.message };
|
|
191
|
+
throw err;
|
|
192
|
+
});
|
|
170
193
|
return { ...collect(session, journey, viewport), ...outcome, cookies: await session.cookies() };
|
|
171
194
|
} finally {
|
|
172
195
|
await session.close();
|
package/src/audit.js
CHANGED
|
@@ -9,6 +9,7 @@ import { LANGUAGES, messages } from "./i18n.js";
|
|
|
9
9
|
import { createProvider } from "./providers.js";
|
|
10
10
|
import { filterFindings, planRun } from "./journeys.js";
|
|
11
11
|
import { resolveProviders } from "./parsers.js";
|
|
12
|
+
import { writeSavedSite } from "./replay.js";
|
|
12
13
|
|
|
13
14
|
export async function readJson(file, baseDir = ".") {
|
|
14
15
|
const full = path.resolve(baseDir, file);
|
|
@@ -48,10 +49,12 @@ export async function writeReports({ outDir, config, plan, runs, findings, expla
|
|
|
48
49
|
/**
|
|
49
50
|
* @param {{ config: any, plan?: any, gtmContainer?: any, journeys?: string[], goals?: string[], events?: string[], viewports?: string[],
|
|
50
51
|
* scripted?: boolean, ai?: boolean, provider?: string, model?: string, baseUrl?: string, maxSteps?: number, lang?: string, headed?: boolean,
|
|
51
|
-
* outDir?: string, branding?: boolean, providers?: string[], log?: (m: string) => void }} opts
|
|
52
|
+
* outDir?: string, branding?: boolean, providers?: string[], saveSite?: string, replaySite?: string, log?: (m: string) => void }} opts
|
|
52
53
|
* journeys: config journey ids or ready-made journeys (purchase, add_to_cart, sign_up, lead, search).
|
|
53
54
|
* goals: extra journeys described in plain language. events: only check these events.
|
|
54
55
|
* providers: tracking providers to check (default: config "providers", else GA4, Google Ads, Meta, TikTok).
|
|
56
|
+
* saveSite: record the site's responses and the steps taken into this folder, for replaySite (see replay.js).
|
|
57
|
+
* replaySite: answer every request from a folder saved with saveSite, without the network.
|
|
55
58
|
*/
|
|
56
59
|
export async function runAudit(opts) {
|
|
57
60
|
const { gtmContainer } = opts;
|
|
@@ -76,17 +79,22 @@ export async function runAudit(opts) {
|
|
|
76
79
|
const provider = useAi ? await createProvider({ name: opts.provider ?? config.provider, model: opts.model ?? config.model, baseUrl: opts.baseUrl ?? config.base_url }) : null;
|
|
77
80
|
if (provider) log(`Using ${provider.name} (${provider.model})`);
|
|
78
81
|
|
|
82
|
+
if (opts.saveSite) await mkdir(opts.saveSite, { recursive: true });
|
|
79
83
|
const runs = [];
|
|
80
84
|
for (const journey of journeys) {
|
|
81
85
|
for (const viewport of viewports) {
|
|
82
86
|
log(`\n▶ ${journey.id} (${viewport})`);
|
|
83
|
-
const run = await runJourney(config, journey, viewport, { scripted: opts.scripted, provider, maxSteps: opts.maxSteps, headed: opts.headed, lang, log });
|
|
87
|
+
const run = await runJourney(config, journey, viewport, { scripted: opts.scripted, provider, maxSteps: opts.maxSteps, headed: opts.headed, lang, log, saveSite: opts.saveSite, replaySite: opts.replaySite });
|
|
84
88
|
log(` ${run.completed ? "✓" : "✗"} ${run.note} · ${run.hits.length} tracking hits captured`);
|
|
85
89
|
runs.push(run);
|
|
86
90
|
}
|
|
87
91
|
}
|
|
88
92
|
|
|
89
93
|
const findings = filterFindings(runs.flatMap((run) => checkRun(plan, run, { lang })), events);
|
|
94
|
+
if (opts.saveSite) {
|
|
95
|
+
await writeSavedSite(opts.saveSite, { config, plan, runs, findings });
|
|
96
|
+
log(`\nSaved the site for offline replay in ${opts.saveSite}`);
|
|
97
|
+
}
|
|
90
98
|
let explained = null;
|
|
91
99
|
if (provider) {
|
|
92
100
|
log("\nAsking the model to explain the findings…");
|
package/src/browser.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { readFile, rm, writeFile } from "node:fs/promises";
|
|
1
2
|
import { chromium, devices } from "playwright";
|
|
2
3
|
import { parseTrackingRequest, isCollectionEndpoint, providerOf, vendorOf, resolveProviders } from "./parsers.js";
|
|
3
4
|
import { redactBody, redactParams, redactPush, redactUrl } from "./redact.js";
|
|
@@ -196,6 +197,62 @@ function trackingBody(request) {
|
|
|
196
197
|
return body ? (body.length > MAX_BODY ? body.slice(0, MAX_BODY) : body) : null;
|
|
197
198
|
}
|
|
198
199
|
|
|
200
|
+
/**
|
|
201
|
+
* How a scripted run can find the element an action used again: the selector it was given,
|
|
202
|
+
* else a CSS path to the element, else its visible text. Refs only mean something in one run.
|
|
203
|
+
*/
|
|
204
|
+
async function replayTarget(a, locator) {
|
|
205
|
+
if (a.selector) return { selector: a.selector };
|
|
206
|
+
const found = await locator
|
|
207
|
+
.evaluate((el) => {
|
|
208
|
+
const text = (el.innerText || el.value || el.getAttribute("aria-label") || "").replace(/\s+/g, " ").trim().slice(0, 80);
|
|
209
|
+
if (window !== window.top) return { text };
|
|
210
|
+
const parts = [];
|
|
211
|
+
for (let n = el; n && n !== document.documentElement; n = n.parentElement) {
|
|
212
|
+
if (n.id && document.querySelectorAll(`#${CSS.escape(n.id)}`).length === 1) {
|
|
213
|
+
parts.unshift(`#${CSS.escape(n.id)}`);
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
let i = 1;
|
|
217
|
+
for (let s = n.previousElementSibling; s; s = s.previousElementSibling) if (s.tagName === n.tagName) i++;
|
|
218
|
+
parts.unshift(`${n.tagName.toLowerCase()}:nth-of-type(${i})`);
|
|
219
|
+
}
|
|
220
|
+
return { selector: parts.join(" > "), text };
|
|
221
|
+
}, null, { timeout: 5000 })
|
|
222
|
+
.catch(() => null);
|
|
223
|
+
if (found?.selector) return { selector: found.selector };
|
|
224
|
+
return found?.text ? { text: found.text } : a.text ? { text: a.text } : {};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Images, fonts and video don't change what tracking sends, and are most of a recording's size.
|
|
228
|
+
const MEDIA = /^(image|font|video|audio)\//;
|
|
229
|
+
|
|
230
|
+
const SECRET_REQUEST_HEADER = /^(cookie|authorization|proxy-authorization)$/i;
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Drops images, fonts, video and tracking requests from a recording (they are answered locally on replay, and their
|
|
234
|
+
* URLs can hold the user data redacted everywhere else), requests with user data in their address, form bodies,
|
|
235
|
+
* cookies both ways and authorization headers.
|
|
236
|
+
*/
|
|
237
|
+
|
|
238
|
+
async function cleanRecording(file) {
|
|
239
|
+
const har = JSON.parse(await readFile(file, "utf8"));
|
|
240
|
+
har.log.entries = har.log.entries
|
|
241
|
+
.filter((e) => !isCollectionEndpoint(e.request.url) && !MEDIA.test(e.response?.content?.mimeType ?? ""))
|
|
242
|
+
// A request whose address holds user data (an email in a form GET, for example) is left out whole.
|
|
243
|
+
.filter((e) => redactUrl(e.request.url).url === e.request.url)
|
|
244
|
+
.map((e) => {
|
|
245
|
+
// Form bodies are dropped; replay then matches POSTs by address and method.
|
|
246
|
+
const { postData: _postData, ...request } = e.request;
|
|
247
|
+
return {
|
|
248
|
+
...e,
|
|
249
|
+
request: { ...request, cookies: [], headers: request.headers.filter((h) => !SECRET_REQUEST_HEADER.test(h.name)) },
|
|
250
|
+
response: { ...e.response, cookies: [], headers: e.response.headers.filter((h) => !/^set-cookie$/i.test(h.name)) },
|
|
251
|
+
};
|
|
252
|
+
});
|
|
253
|
+
await writeFile(file, JSON.stringify(har));
|
|
254
|
+
}
|
|
255
|
+
|
|
199
256
|
export class AuditSession {
|
|
200
257
|
/**
|
|
201
258
|
* @param {{ viewport: string, site?: string, allowedHosts?: string[], providers?: string[], keepBodies?: boolean, blockPrivate?: boolean | ((ip: string) => boolean), blockHits?: boolean, headless?: boolean }} opts
|
|
@@ -204,6 +261,8 @@ export class AuditSession {
|
|
|
204
261
|
* providers: which tracking providers to record (default GA4, Google Ads, Meta, TikTok). Requests to the
|
|
205
262
|
* others are still answered locally, but only counted, per step, in this.skipped.
|
|
206
263
|
* site: navigation is limited to this site's host and its subdomains, plus allowedHosts.
|
|
264
|
+
* recordHar: save every response the site sends into this .har file, so the journey can be replayed offline later.
|
|
265
|
+
* replayHar: answer requests from a .har file saved with recordHar instead of the network; requests it lacks fail.
|
|
207
266
|
* blockPrivate: refuse loopback, private and link-local addresses (used when the MCP server is reachable over HTTP).
|
|
208
267
|
* All browser traffic then goes through the egress proxy. A function decides which addresses count as private (for tests).
|
|
209
268
|
*/
|
|
@@ -240,7 +299,8 @@ export class AuditSession {
|
|
|
240
299
|
launch.args = ["--force-webrtc-ip-handling-policy=disable_non_proxied_udp"];
|
|
241
300
|
}
|
|
242
301
|
this.browser = await chromium.launch(launch);
|
|
243
|
-
this.
|
|
302
|
+
const record = this.opts.recordHar ? { recordHar: { path: this.opts.recordHar, mode: "minimal" } } : {};
|
|
303
|
+
this.context = await this.browser.newContext({ ...device, locale: "en-US", ...record });
|
|
244
304
|
await this.context.exposeBinding("__atdRecord", (_source, entry) => {
|
|
245
305
|
this.record("dataLayerLog", { ...this.redactEntry(entry), step: this.currentStep, t: Date.now() });
|
|
246
306
|
});
|
|
@@ -315,6 +375,8 @@ export class AuditSession {
|
|
|
315
375
|
// the page navigates away (a page_view on the next load, a beacon on unload) can be
|
|
316
376
|
// cancelled before its route handler runs, but its request event has already fired.
|
|
317
377
|
this.context.on("request", onRequest);
|
|
378
|
+
// Registered first, so the routes below run before it and tracking requests are still answered locally.
|
|
379
|
+
if (this.opts.replayHar) await this.context.routeFromHAR(this.opts.replayHar, { notFound: "abort" });
|
|
318
380
|
if (this.opts.blockHits) {
|
|
319
381
|
await this.context.route((url) => isCollectionEndpoint(url.href), async (route) => {
|
|
320
382
|
await route.fulfill({ status: 204, body: "" });
|
|
@@ -598,12 +660,14 @@ export class AuditSession {
|
|
|
598
660
|
async act(a) {
|
|
599
661
|
const describe = a.reason || `${a.action} ${a.selector ?? (a.ref != null ? `#${a.ref}` : a.text != null ? `"${a.text}"` : a.url ?? "")}`.trim();
|
|
600
662
|
this.beginStep(describe, { action: a.action, acceptsConsent: !!a.accepts_consent });
|
|
663
|
+
const step = this.steps[this.currentStep];
|
|
601
664
|
try {
|
|
602
665
|
switch (a.action) {
|
|
603
666
|
case "goto": {
|
|
604
667
|
const target = new URL(a.url, this.page.url() === "about:blank" ? undefined : this.page.url()).href;
|
|
605
668
|
const refused = await this.checkUrl(target);
|
|
606
669
|
if (refused) return refused;
|
|
670
|
+
step.replay = { action: "goto", url: target };
|
|
607
671
|
await this.page.goto(target, { waitUntil: "domcontentloaded", timeout: 30000 });
|
|
608
672
|
break;
|
|
609
673
|
}
|
|
@@ -617,12 +681,14 @@ export class AuditSession {
|
|
|
617
681
|
if (found.error) return found.error;
|
|
618
682
|
target = found.locator;
|
|
619
683
|
} else return `${a.action} needs a ref or the element's visible text.`;
|
|
684
|
+
step.replay = { action: a.action, ...(await replayTarget(a, target)), ...(a.value !== undefined ? { value: a.value } : {}) };
|
|
620
685
|
if (a.action === "click") await this.click(target);
|
|
621
686
|
else if (a.action === "fill") await target.fill(a.value ?? "", { timeout: 10000 });
|
|
622
687
|
else await target.selectOption(a.value ?? "", { timeout: 10000 });
|
|
623
688
|
break;
|
|
624
689
|
}
|
|
625
690
|
case "scroll": {
|
|
691
|
+
step.replay = { action: "scroll", ...(a.value !== undefined ? { value: a.value } : {}) };
|
|
626
692
|
const dy = /^up$/i.test(a.value ?? "") ? -900 : 900;
|
|
627
693
|
const size = this.page.viewportSize() ?? { width: 800, height: 600 };
|
|
628
694
|
const before = await this.page.evaluate(() => window.scrollY);
|
|
@@ -634,6 +700,7 @@ export class AuditSession {
|
|
|
634
700
|
break;
|
|
635
701
|
}
|
|
636
702
|
case "wait":
|
|
703
|
+
step.replay = { action: "wait", ...(a.value !== undefined ? { value: a.value } : {}) };
|
|
637
704
|
await this.page.waitForTimeout(Math.min(Number(a.value) || 1000, 10000));
|
|
638
705
|
break;
|
|
639
706
|
default:
|
|
@@ -654,6 +721,12 @@ export class AuditSession {
|
|
|
654
721
|
}
|
|
655
722
|
|
|
656
723
|
async close() {
|
|
724
|
+
if (this.opts.recordHar && this.context) {
|
|
725
|
+
// Writes the recording. If the browser already went away, there is none to clean.
|
|
726
|
+
const written = await this.context.close().then(() => true, () => false);
|
|
727
|
+
// A recording that could not be cleaned may hold cookies or form data, so it is deleted.
|
|
728
|
+
if (written) await cleanRecording(this.opts.recordHar).catch(() => rm(this.opts.recordHar, { force: true }));
|
|
729
|
+
}
|
|
657
730
|
await this.browser?.close();
|
|
658
731
|
await this.egress?.close();
|
|
659
732
|
}
|
package/src/cli.js
CHANGED
|
@@ -6,6 +6,7 @@ import { LANGUAGES, messages } from "./i18n.js";
|
|
|
6
6
|
import { PROVIDERS } from "./providers.js";
|
|
7
7
|
import { JOURNEY_PRESETS } from "./journeys.js";
|
|
8
8
|
import { PROVIDERS as TRACKING_PROVIDERS, DEFAULT_PROVIDERS } from "./parsers.js";
|
|
9
|
+
import { replaySavedSite } from "./replay.js";
|
|
9
10
|
|
|
10
11
|
const USAGE = `ai-tag-debugger: an open-source AI agent that QA-tests your analytics and ad tracking.
|
|
11
12
|
|
|
@@ -13,6 +14,8 @@ Usage:
|
|
|
13
14
|
ai-tag-debugger run --site <url> --journey purchase [options] Audit ready-made journeys, no config needed.
|
|
14
15
|
ai-tag-debugger run --site <url> --goal "<what to do>" Audit a journey you describe in plain language.
|
|
15
16
|
ai-tag-debugger run --config <file> [options] Run an audit from a config file.
|
|
17
|
+
ai-tag-debugger replay <dir>... [--update] Audit sites saved with --save-site again, offline and without AI,
|
|
18
|
+
and list findings that changed. Exits with code 1 when any did.
|
|
16
19
|
ai-tag-debugger mcp [--http] [--port <n>] Start the MCP server for Claude, ChatGPT, Gemini and other chat apps.
|
|
17
20
|
|
|
18
21
|
Run options:
|
|
@@ -41,6 +44,12 @@ Run options:
|
|
|
41
44
|
--keep-bodies Store tracking requests as sent. By default, emails, phone numbers and user ids sent
|
|
42
45
|
for ad matching are redacted in the report and capture.json ("keep_bodies" in the config).
|
|
43
46
|
--no-branding Leave the Analitik İşler logo and credit line out of the reports ("branding": false in the config).
|
|
47
|
+
--save-site <dir> Also save the site's responses and the steps taken in this folder, so "replay" can audit
|
|
48
|
+
the same pages again offline. Its findings become the expected ones.
|
|
49
|
+
|
|
50
|
+
Replay options:
|
|
51
|
+
--update Make this replay's findings the expected ones (after checking that the changes are right).
|
|
52
|
+
--out <dir> Where to write the replay's reports (default: <dir>/last-replay).
|
|
44
53
|
|
|
45
54
|
MCP options:
|
|
46
55
|
--http Serve over Streamable HTTP instead of stdio (for apps that connect to a URL).
|
|
@@ -87,6 +96,8 @@ async function main() {
|
|
|
87
96
|
token: { type: "string" },
|
|
88
97
|
reports: { type: "string" },
|
|
89
98
|
"public-url": { type: "string" },
|
|
99
|
+
"save-site": { type: "string" },
|
|
100
|
+
update: { type: "boolean", default: false },
|
|
90
101
|
help: { type: "boolean", short: "h", default: false },
|
|
91
102
|
},
|
|
92
103
|
});
|
|
@@ -97,6 +108,22 @@ async function main() {
|
|
|
97
108
|
await startMcp({ http: values.http, port: values.port ? Number(values.port) : undefined, host: values.host, token: values.token, reportsDir: values.reports, publicUrl: values["public-url"], allowPrivateNetwork: values["allow-private-network"] });
|
|
98
109
|
return;
|
|
99
110
|
}
|
|
111
|
+
if (command === "replay" && !values.help) {
|
|
112
|
+
const dirs = positionals.slice(1);
|
|
113
|
+
if (!dirs.length) throw new Error("replay needs the folder of at least one site saved with --save-site.");
|
|
114
|
+
let changed = false;
|
|
115
|
+
for (const dir of dirs) {
|
|
116
|
+
const r = await replaySavedSite(dir, { update: values.update, outDir: dirs.length === 1 ? values.out : undefined });
|
|
117
|
+
const same = !r.missing.length && !r.extra.length;
|
|
118
|
+
changed ||= !same;
|
|
119
|
+
console.log(`${same ? "✓" : values.update ? "↻" : "✗"} ${r.site} (${dir}): ${same ? "same findings" : `${r.extra.length} new, ${r.missing.length} gone${values.update ? ", saved as expected" : ""}`}`);
|
|
120
|
+
for (const k of r.extra) console.log(` + ${k}`);
|
|
121
|
+
for (const k of r.missing) console.log(` - ${k}`);
|
|
122
|
+
for (const note of r.incomplete) console.log(` ! ${note}`);
|
|
123
|
+
}
|
|
124
|
+
if (changed && !values.update) process.exitCode = 1;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
100
127
|
if (values.help || command !== "run" || (!values.config && !values.site)) {
|
|
101
128
|
console.log(USAGE);
|
|
102
129
|
process.exit(values.help ? 0 : 2);
|
|
@@ -136,6 +163,7 @@ async function main() {
|
|
|
136
163
|
headed: values.headed,
|
|
137
164
|
branding: values["no-branding"] ? false : undefined,
|
|
138
165
|
outDir: values.out,
|
|
166
|
+
saveSite: values["save-site"],
|
|
139
167
|
log: (msg) => console.log(msg),
|
|
140
168
|
});
|
|
141
169
|
|
package/src/parsers.js
CHANGED
|
@@ -35,9 +35,10 @@ export function parseGa4(url, postData) {
|
|
|
35
35
|
// Matched on the GA4 protocol rather than the host, so server-side GTM
|
|
36
36
|
// endpoints on first-party domains are captured too.
|
|
37
37
|
if (!u.pathname.endsWith("/g/collect") || u.searchParams.get("v") !== "2") return null;
|
|
38
|
-
// gtag.js resends a hit to www.google.com/g/collect
|
|
39
|
-
//
|
|
40
|
-
|
|
38
|
+
// gtag.js resends a hit to www.google.com/g/collect when the first send seems lost, and
|
|
39
|
+
// copies some to doubleclick.net. GA4 doesn't count these twice, so they aren't hits.
|
|
40
|
+
// (Primary hits can carry gaf too, e.g. gaf=2, so the host decides, not the parameter.)
|
|
41
|
+
if (GOOGLE_COMPANION_HOST.test(u.hostname)) return null;
|
|
41
42
|
const base = new URLSearchParams(u.search);
|
|
42
43
|
const lines = postData ? postData.split("\n").filter(Boolean) : [""];
|
|
43
44
|
return lines.map((line) => {
|
|
@@ -135,8 +136,12 @@ export function parseTrackingRequest(url, postData) {
|
|
|
135
136
|
// hits: Google Ads remarketing and consent pings, and the other common ad pixels.
|
|
136
137
|
const OTHER_BEACONS = [
|
|
137
138
|
[/(^|\.)(doubleclick\.net|googleadservices\.com|google\.[a-z.]+)$/, /^\/pagead\/(viewthroughconversion|1p-user-list|landing)\//],
|
|
138
|
-
[/(^|\.)google\.[a-z.]+$/, /^\/
|
|
139
|
+
[/(^|\.)google\.[a-z.]+$/, /^\/rmkt\/collect\//],
|
|
139
140
|
[GOOGLE_COMPANION_HOST, /\/g\/collect$/],
|
|
141
|
+
[/(^|\.)merchant-center-analytics\.goog$/, /^\/mc\/collect/],
|
|
142
|
+
// Google tag pings on any host: consent mode (ccm), the Google tag's own /g/s/collect, and
|
|
143
|
+
// Google tag gateway paths served from the site's own domain (/<id>/gs/ccm/collect).
|
|
144
|
+
[/./, /\/(ccm|ccm\/s|g\/s)\/collect$/],
|
|
140
145
|
[/^td\.doubleclick\.net$/, /^\/td\//],
|
|
141
146
|
[/(^|\.)facebook\.com$/, /^\/privacy_sandbox\/pixel\//],
|
|
142
147
|
[/^bat\.bing\.com$/, /^\/action\//],
|
package/src/replay.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Saved sites: the responses a site sent during an audit and the steps taken, so a later
|
|
2
|
+
// version of the tool can audit the same pages offline and show what it now reports
|
|
3
|
+
// differently. Replays need no network and no AI model, so they cost nothing.
|
|
4
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { runAudit } from "./audit.js";
|
|
7
|
+
|
|
8
|
+
export const SAVED_SITE_FILE = "site.json";
|
|
9
|
+
|
|
10
|
+
/** The steps a run took, as fixed steps a scripted run can repeat. */
|
|
11
|
+
export function replayableJourney(run) {
|
|
12
|
+
const steps = run.steps.filter((s) => s.index > 0);
|
|
13
|
+
const start = steps[0]?.replay?.action === "goto" ? steps[0].replay.url : undefined;
|
|
14
|
+
return {
|
|
15
|
+
id: run.journeyId,
|
|
16
|
+
viewport: run.viewport,
|
|
17
|
+
...(start ? { start } : {}),
|
|
18
|
+
steps: (start ? steps.slice(1) : steps)
|
|
19
|
+
.filter((s) => s.replay)
|
|
20
|
+
.map((s) => ({ ...s.replay, reason: s.label, ...(s.acceptsConsent ? { accepts_consent: true } : {}) })),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** One line per finding, sorted: what a replay is compared on. */
|
|
25
|
+
export function findingKeys(findings) {
|
|
26
|
+
return findings.map((f) => [f.severity, f.check, f.journey, f.viewport, f.platform ?? "-", f.event ?? "-"].join(" ")).sort();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Lines in one list and not the other, counting repeats. */
|
|
30
|
+
export function compareKeys(expected, actual) {
|
|
31
|
+
const left = [...actual];
|
|
32
|
+
const missing = [];
|
|
33
|
+
for (const k of expected) {
|
|
34
|
+
const i = left.indexOf(k);
|
|
35
|
+
if (i === -1) missing.push(k);
|
|
36
|
+
else left.splice(i, 1);
|
|
37
|
+
}
|
|
38
|
+
return { missing, extra: left };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Writes site.json next to the recorded responses. The findings of this run become the expected ones. */
|
|
42
|
+
export async function writeSavedSite(dir, { config, plan, runs, findings }) {
|
|
43
|
+
await mkdir(dir, { recursive: true });
|
|
44
|
+
const { journeys: _journeys, plan: _plan, gtm_container: _gtm, ...site } = config;
|
|
45
|
+
const saved = {
|
|
46
|
+
version: 1,
|
|
47
|
+
saved_at: new Date().toISOString(),
|
|
48
|
+
config: site,
|
|
49
|
+
plan,
|
|
50
|
+
journeys: runs.map(replayableJourney),
|
|
51
|
+
expected: findingKeys(findings),
|
|
52
|
+
};
|
|
53
|
+
await writeFile(path.join(dir, SAVED_SITE_FILE), JSON.stringify(saved, null, 2));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Audits a saved site again, offline and without AI, and compares the findings with the expected ones.
|
|
58
|
+
* update: make this replay's findings the expected ones.
|
|
59
|
+
* @returns {Promise<{ site: string, missing: string[], extra: string[], reportPaths: string[], incomplete: string[] }>}
|
|
60
|
+
*/
|
|
61
|
+
export async function replaySavedSite(dir, { update = false, outDir, log = () => {} } = {}) {
|
|
62
|
+
const file = path.join(dir, SAVED_SITE_FILE);
|
|
63
|
+
let saved;
|
|
64
|
+
try {
|
|
65
|
+
saved = JSON.parse(await readFile(file, "utf8"));
|
|
66
|
+
} catch (err) {
|
|
67
|
+
throw new Error(`Could not read ${file}: ${err.message}`);
|
|
68
|
+
}
|
|
69
|
+
const viewports = [...new Set(saved.journeys.map((j) => j.viewport))];
|
|
70
|
+
const findings = [];
|
|
71
|
+
const reportPaths = [];
|
|
72
|
+
const incomplete = [];
|
|
73
|
+
for (const viewport of viewports) {
|
|
74
|
+
const journeys = saved.journeys.filter((j) => j.viewport === viewport).map(({ viewport: _v, ...j }) => j);
|
|
75
|
+
const out = path.resolve(outDir ?? path.join(dir, "last-replay"), viewports.length > 1 ? viewport : "");
|
|
76
|
+
const result = await runAudit({
|
|
77
|
+
config: { ...saved.config, journeys },
|
|
78
|
+
plan: saved.plan,
|
|
79
|
+
viewports: [viewport],
|
|
80
|
+
scripted: true,
|
|
81
|
+
ai: false,
|
|
82
|
+
replaySite: dir,
|
|
83
|
+
lang: "en",
|
|
84
|
+
outDir: out,
|
|
85
|
+
log,
|
|
86
|
+
});
|
|
87
|
+
findings.push(...result.findings);
|
|
88
|
+
reportPaths.push(result.reportPath);
|
|
89
|
+
incomplete.push(...result.runs.filter((r) => !r.completed).map((r) => `${r.journeyId} (${r.viewport}): ${r.note}`));
|
|
90
|
+
}
|
|
91
|
+
const actual = findingKeys(findings);
|
|
92
|
+
const { missing, extra } = compareKeys(saved.expected ?? [], actual);
|
|
93
|
+
if (update && (missing.length || extra.length)) {
|
|
94
|
+
await writeFile(file, JSON.stringify({ ...saved, expected: actual }, null, 2));
|
|
95
|
+
}
|
|
96
|
+
return { site: saved.config.site, missing, extra, reportPaths, incomplete };
|
|
97
|
+
}
|