Repository navigation
feat(traffic): take a journey's pageviews and conversions from the AI Traffic snippet (CE-017, part 1: server) - #1527
Conversation
… Traffic snippet, for brands with conversions on (CE-017, part 1: server) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rder id sent first by anyone can't shut the real one out; keep no label or order ref that looks personal; check an event before reading the brand (pre-push review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
gkhngyk
left a comment
There was a problem hiding this comment.
Needs changes.
What I checked:
- Visits are untouched.
pvandcvbranch off after the brand lookup and before the address is read. A journey event never computes or stores an IP, a visitor key, a country or a user agent. A body withoutk, or withk: "nf", takes the old path. Today's snippet never sendspvorcv, so deploying this changes nothing until part 2 ships. - Who can write what.
- The brand comes from the tracking code alone, so an event lands only on the brand whose code it carries.
- The answer is 204 whether the event was stored or not, so it doesn't tell anyone whether a brand has conversions on.
- With conversions off, nothing is stored.
- A server running before 00286 fails only these events and logs them. Visits are still stored (tested).
- The body.
- It's read with a zod schema, and unknown keys are dropped. The visitor id must match
[A-Za-z0-9_-]{16,64}. Goals and origins come from fixed lists. - Value is 0 to 1e9, which fits
numeric(14,2). Units are 0 to 100,000. A currency is kept only with a value, and only as three letters. - A page, and the first visit's landing page, keep only their origin and path. Sign-in details go with the origin.
- A label is dropped if it has an
@, a+, brackets or a run of seven digits. - The source must be on the AI list, and the first visit must be within 30 days and not in the future. Anything else is dropped before the brand is read.
- The beacon body is capped at 64 kb. The 60-a-minute limit per address covers these events too.
- It's read with a zod schema, and unknown keys are dropped. The visitor id must match
- Logs. A failed insert logs only the database's message, never the row. An order sent again (23505) isn't logged.
- 00286.
- RLS is on. anon and authenticated lose the default grants, authenticated gets
selectback, and service_role writes. The one policy is the same membership read asai_traffic_logs's. - Turning conversions on is an update to
brands, which RLS keeps to admins and managers. - The checks match the server's bounds, and the kind check keeps goal, origin and order ref off pageviews.
- It's safe to run again (
if not exists,drop policy if exists). The two newbrandscolumns have constant defaults, so adding them only checks a small table once. - A write reads only the brand, by
idx_brands_tracking_codeand by primary key. The journey index is the one 00287 and 00288 read a visitor's pages through. schema.sqlis the build script's output.
- RLS is on. anon and authenticated lose the default grants, authenticated gets
- Merge. It's built on current main and merges cleanly. Once #1514 lands, only
schema.sqlconflicts.
Before merge:
server/src/lib/traffic-events.js:56-64: the query string and the fragment go, but the path is kept as is, and a path can hold an email (/unsubscribe/[email protected],/account/ann%40example.com). The Live page tab would then show it in a journey.- Fix: give the path the same check as the label. Replace any segment that holds an
@, raw or as%40, with a fixed placeholder. The page still counts, and the address stays out. - That covers
first_urltoo. Add a test.
- Fix: give the path the same check as the label. Replace any segment that holds an
server/src/routes/traffic.js:231-248: beyond the per-address limit, nothing bounds how many rows one visitor id, or one tracking code, can store. Tighten that, so the table and the journey reads (00287, 00288) stay bounded whatever a sender does:- Per visitor id: skip a pageview once the visitor already has a few hundred in the attribution window, and keep a visitor's conversions to a few a day. The journey index answers both with a short
limited read. - Per tracking code: add a limiter for
pvandcv, keyed by the code, and sized well above a big shop's AI pageviews. - Add tests.
- Per visitor id: skip a pageview once the visitor already has a few hundred in the attribution window, and keep a visitor's conversions to a few a day. The journey index answers both with a short
Follow-ups:
3. server/src/lib/traffic-events.js:79-83 and :123: order_ref is only ever compared (the unique index), and nothing reads it back.
- Fix: store a hash of it (for example sha256 of the brand id and the ref) instead of the ref itself. It still fits the 128-character check.
- Then neither a checkout token nor a number that isn't an order is ever kept as is. Part 3's pixel sends the checkout token when Shopify gives no order id.
supabase/migrations/00286_ai_traffic_conversions.sql:70-71:ai_traffic_events_brand_timehas no reader in this stack, because 00287 adds its own partial index for conversions. Every pageview still pays for it. Nothing deletes events either, as with visits.- Fix: drop the index, or keep it for a sweep that deletes events older than the longest window the reads use (366 days in 00287). Say the period in the docs.
…id and one tracking code can store, keep an order's id only as a hash, and drop an index nothing reads (review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
… journey's reads compare keys instead of working each address out again (review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…se that ran 00286 before them, and keep a handle such as /@acme in a path: only an email goes (review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, all four are in (fb41530). Before merge
Follow-ups, done here One more, for #1530/#1531's reads. Each event now stores its pages' keys as generated columns: 00286 edited in place. It isn't merged and isn't on prod, so I edited it rather than adding a migration, and re-applied it on the dev database. In case a database ran the older 00286, it now also adds The path rule replaces only a segment shaped like an email (a name, an Server: |
gkhngyk
left a comment
There was a problem hiding this comment.
Needs changes.
What I checked:
- Earlier items.
- Done, with one change to the new check (item 1 below) (6c089db, fb41530).
eventUrlstores a path segment that holds an email, raw or as%40in any case, as[email]. The page still counts, andfirst_urlis read the same way.- A handle such as
/@acme/postkeeps its segment, so its page still matches on the Live page tab. - Tests cover the raw, encoded and upper-case forms, a handle, and
first_url.
- Done (6c089db).
- Per visitor id.
storeEvent(routes/traffic.js:235) reads the visitor's earlier events of the same kind throughai_traffic_events_journey,limited to the cap. It stores no more past 300 pageviews in the 30-day window or 10 conversions a day.kindisn't in the index, so the read walks the visitor's rows in the window, and the caps keep those to a few hundred. Two events at once can pass the cap by one, which is harmless. - Per tracking code.
journeyEventLimiter(rate-limiter.js:205) allows 3,000 a minute per code. It counts onlypvandcv, after the 64 KB read, and answers 204 past the cap. A sender can use up a brand's minute, and the brand's real events for that minute are then dropped. That's the trade a per-code cap makes, and the per-address limit still applies to every sender. - Tests cover the read's filters, both caps,
isJourneyBeaconandjourneyEventKey.
- Per visitor id.
- Done.
order_refissha256(brand id + ":" + the shop's id), 64 hex characters, inside the 128-character check. The unique index compares hashes, and nothing reads the column back. #1532's docs don't describe it as the raw id. - Done. The index is gone from the
create, anddrop index if existsremoves it from a database that ran the older file. With the index gone, keeping events like visits is fine.
- Done, with one change to the new check (item 1 below) (6c089db, fb41530).
- The page keys (934227c).
page_keyandfirst_keyarelower(normalize_page_path(...)), stored on insert.normalize_page_pathis immutable and unchanged since 00075.- It never raises:
url_decode_safereturns the input when it can't decode it. So an odd address never fails an insert. - The keys are made from the stored address, after the
[email]swap.
- 00286 edited in place.
- It isn't on prod, so editing it is fine.
- On a fresh run, the
add column if not existsis a no-op. On a database that ran the older file, the same run adds the keys and drops the index. schema.sqlmirrors it, and CI's schema check passes.
- Merge.
- There are no merge commits. On 4085418 (with #1533), it merges cleanly.
- After the merge, a beacon goes through the per-address limiter, then the 64 KB text read for every content type, then the per-code limiter, then the handler.
isJourneyBeaconalways gets the string. #1533's two tests use the same mocks, and the mocks now includejourneyEventLimiter. - On today's main (with #1514 and #1515), only
schema.sqlconflicts. - CI passes at fb41530.
- Before the API is deployed. This PR is server and migration only, so users see no change. After the deploy, nothing sends
pvorcvuntil part 2 ships.
Before merge:
server/src/lib/traffic-events.js:68and:81-84: replaceEMAIL_IN_SEGMENTwith a single pass over each segment. The check runs on any sender's address, up to 16 KB.- For example:
function holdsEmail(segment) { let text; try { text = decodeURIComponent(segment); } catch { text = segment.replace(/%40/gi, '@'); // a malformed escape elsewhere in it } const at = text.indexOf('@', 1); // an @ at the start is a handle return at > 0 && text.indexOf('.', at + 2) > 0; }
- It keeps
/@acmeand/@acme.dev, and catches everything the pattern catches. - Decoding first also catches an encoded dot (
ann%40example%2Ecom). Today the pattern misses that segment, andpage_keystores it decoded as[email protected]. - Tests: keep the current cases, and add
ann%40example%2Ecom. Add a 16 KB path that's checked in a few milliseconds.
- For example:
…ersion-events # Conflicts: # supabase/schema.sql
|
Merged Checks after the merge:
|
…irst, so a long address reads fast and an encoded dot is caught (review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ush review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done (879538c):
The fix is merged up through #1528–#1531. Checks: server format and lint clean, 224 test files, 2,795 passed, 3 skipped. At #1531: web 427 files, 4,020 passed, build OK, and server tests passed. |
gkhngyk
left a comment
There was a problem hiding this comment.
Needs changes.
What I checked:
- Earlier item.
- Partly (d4a48f6, 879538c).
holdsEmail(server/src/lib/traffic-events.js:73-83) replacesEMAIL_IN_SEGMENT.- It decodes the segment first. When an escape is malformed, it reads the segment's
%40and%2Eas@and.(:79). - An @ at the start is a handle, so
/@acmeand/@acme.devkeep their segment (traffic-events.test.js:64-65). - It catches
ann%40example%2Ecom, and also the same segment with a malformed escape after it (:29,:60). - It catches every segment the old pattern caught:
- The pattern needed a character before the @ and one between the @ and a dot.
at > 0andat + 2still ask for both, and decoding never makes a part empty. - I ran 200,000 random segments built from @, dots,
%40,%2E, and valid and malformed escapes. The new check missed none that the pattern caught.
- The pattern needed a character before the @ and one between the @ and a dot.
- The work grows linearly with the input: one decode (or two replaces), then two
indexOfcalls. A 16 KB segment takes about 0.02 ms. The old pattern took about 420 ms on the same segment. - One cost is left (item 1 below).
- It decodes the segment first. When an escape is malformed, it reads the segment's
- Partly (d4a48f6, 879538c).
- The rest of the path. I read every regex and loop a beacon meets on
/track/:code(routes/traffic.js,traffic-events.js,rate-limiter.js,ai-sources.js):- The visitor id's pattern is anchored, with one character class.
eventLabelandorderRefread at most 80 and 200 characters. Their patterns are anchored, with one class each.classifyAiSourcecompares at most 255 characters with the source list.landingMediumwalks a query string of at most 2,048 characters.- The body is parsed twice, by
isJourneyBeaconand by the route. Each parse is linear in its 64 KB. - None of these does more than linear work.
- 00286 hasn't changed since round 31: the file is the same at fb41530 and 879538c.
- Merge of main (995fe1b).
- Re-merging its parents (fb41530 and 4efa150) gives the same tree, apart from
supabase/schema.sql, the one conflict. - The committed
schema.sqlis exactly whatbuild-schema.shbuilds from the migrations at 995fe1b: 00285 from main, then 00286. The same holds at 879538c. I rebuilt it from the files at each commit, without running the script. - The PR merges cleanly on 4efa150. On today's main (a443462, with 00289), only
schema.sqlconflicts. - CI passes at 879538c.
- Re-merging its parents (fb41530 and 4efa150) gives the same tree, apart from
- Before the API is deployed. This PR is server and migration only, so users see no change.
Before merge:
server/src/lib/traffic-events.js:75-80: bound the work on a long address that has many segments.decodeURIComponentthrows on a segment with a malformed escape, and a throw costs far more than the scan. On an address split into many short segments, those throws add up, and an event has two addresses.- Read the encoded @ and dot directly, with no decode. The answer is the same for every segment: an escape always decodes to at least one character, and only
%40and%2Edecode to an @ or a dot.export function holdsEmail(segment) { // Its @ and dots, raw or encoded: no other escape makes either. const text = segment.replace(/%40/gi, '@').replace(/%2e/gi, '.'); const at = text.indexOf('@', 1); // an @ at the start is a handle return at > 0 && text.indexOf('.', at + 2) > 0; }
- On 200,000 random segments, it gives the current check's answer every time, and its time stays linear in the address.
- Tests: keep the current cases. Add a timing test for
eventUrlon a 16 KB address of many short segments with malformed escapes: it should finish within a few milliseconds.
…ng it, so an address of many segments with malformed escapes reads in linear time (review) Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Done (978e51a): New test: Checks: server format and lint clean; 224 test files, 2,796 passed, 3 skipped. I haven't merged |
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good, with a follow-up.
What I checked:
- Round 32's before-merge item: done (978e51a).
holdsEmailreads the segment's%40and%2Eas they are, with no decode, so a malformed escape costs nothing and the read is linear in the address. Its answer is the decoded one's for every segment, as the comment says. - Tests. The earlier cases stay, including the encoded dot and the malformed escape, and a 16 KB address of 3,200 short segments with malformed escapes is read with its email swapped for
[email]. - Nothing else changed in the commit:
traffic-events.jsand its test. - Migration 00286 is unchanged; it's applied on prod just before this merge.
- Merge. On today's main only
schema.sqlconflicts; the merge commit rebuilds it withbuild-schema.sh, putting 00286 after 00290. The combined tree with the rest of the chain passes server and web tests, tsc, lint, Prettier and the schema build.
Follow-up:
traffic-events.test.js: the new timing test's limit is 8 ms. On a busy CI runner that can fail with nothing wrong. A limit of 100 ms still catches the decode-per-segment shape on a longer address, or compare against a plain address of the same length.
Summary
CE-017, part 1 of 6: server. Conversion tracking from the AI Traffic snippet (Content Editor spec v2, §7b): follow a visitor who came from an AI assistant through the site to a goal, so the Live page tab can show what a page earns from AI visits and the journeys that got there.
The owner approved these choices:
waitmode only after the site's consent (its banner, or Google Consent Mode).?email=…never gets in.This PR is server only:
Migration
00286_ai_traffic_conversions.sqlbrands.conversions_enabled(defaultfalse) andbrands.conversions_consent(wait|always, defaultwait).ai_traffic_events: a journey's pageviews and conversions. Each row has:signup,demo,order,booking,newsletter,custom), label, origin (call,form,shopify), value, currency, units, order ref;POST /track/:codepv(a journey pageview) andcv(a conversion).lib/traffic-events.js).kabsent) and soft-404 marks (k: "nf") work exactly as before.The next parts: the snippet (visitor id, journey pages, forms,
ansvisor('conversion', …), consent, GTM), the Shopify pixel, the Settings section, the Live page tab and Plan strip, and docs.Related issue
Content Editor spec v2, CE-017 (§7b points 31–35).
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
00286and setconversions_enabled = trueon a test brand.POST /track/<tracking_code>(body astext/plain):{"k":"cv","id":"Vq3xT0mZ8kLp2RwYbN5sQa","u":"https://site.example/[email protected]","f":{"s":"chatgpt.com","u":"https://site.example/blog","at":<now ms>},"g":"demo","o":"form"}ai_traffic_eventswithurl = https://site.example/thanks(no query string) andfirst_source = chatgpt.com.f.snot an AI source, nothing is stored. A secondcvwith the sameidandrefadds no row.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdnpm run lintpasses (run fromserver/)npm testpasses (run fromserver/)bash supabase/build-schema.shrun andsupabase/schema.sqlincludedMigration applied on the dev database. Its constraints were tried there in a rolled-back transaction: a second insert of the same order is refused, and a pageview with a goal is refused. A pre-push review ran; its fixes are the last commit (per-visitor order index, label and order ref checks, check before the brand read, a test for a server before the migration).
🤖 Generated with Claude Code