Affiliate and referral tracking
Referral tracking, affiliate signup, and a payout-ready ledger
Gives each promoter their own link, counts the signups it brings in and works out what they are owed. Taken from a referral system live in a real product.
A feature of the Playground
This is a feature of the Vibe Coder Playground. It runs inside the Playground, with its audit record and its caveats beside it.
The mistake it removes
Referral attribution is money, so the failure modes are money-shaped. The three that bite: SELF-REFERRAL (an affiliate buys through their own link), an attribution window with no upper bound (a cookie set once earns commission forever), and a commission recorded before the payment settles: a refunded order that already paid out. The first two are refused in recordConversion() and named in the code. The third is handled by order of calls plus a reversal: record only after the charge settles, keep the row pending through your refund window, and call reverse() from your refund webhook, which moves the commission to reversed and writes an audit row. Each of these is invisible until an invoice is wrong.
What the audit found
Named rather than summarized. The reasoning behind each one ships inside the block, so it travels with the code instead of living on a page you have to trust. A finding marked fixed was fixed after the audit ran; the verdict above is still the one the audit gave.
- me() discloses an affiliate's earnings behind a public identifier major · Security (authorization) / Privacy Fixed after the audit in
24d0bc2c7 - A conversion with an unparseable or negative amount is written as a $0 row, acked ok:true, and the order id is then burnt for the corrected retry major · Correctness (money) Fixed after the audit in
1021d79cb - No shipped path approves an affiliate or moves a conversion to payable, paid or reversed; block.json says the refund case is 'handled here' minor · Reachability / Claims Fixed after the audit in
1be05051c - affiliateLink() with a base that already carries a query string produces a double '?' minor · Correctness Fixed after the audit in
9b3e3cadf - dd.json checkedAt is stale by its own definition, and the suite can die mid-run instead of reporting minor · Verification integrity Fixed after the audit in
d93bdf468
What you still have to do
The feature cannot own your secrets, your host or your legal obligations. This is the part it deliberately does not claim.
- The referral code is public, because it sits in every share link, so it cannot unlock earnings. me() refuses a bare code with a 401 and answers only when the caller also sends the dashboard token apply() returned at signup. Only a hash of that token is stored. Your dashboard page must keep the token and send it in a header. This holds until your app has real sessions; then check the session instead. A lost token cannot be recovered from the database, and this block ships no reset flow.
- An email address belongs to whoever reads its inbox, not to whoever typed it first. apply() mails a confirmation token to the address through your notify hook, and approve() refuses a row whose address was never confirmed (reason 'email-unverified'), so someone who signs up with another person's email and their own payout address can never be approved. verifyEmail(code, token, { payTo }) confirms the address and returns a new dashboard token, which replaces the one apply() returned. The payout address belongs to the inbox owner too: verifyEmail() refuses to confirm without a payTo and writes the one it is given in the same step, replacing whatever the first applicant typed. Ask for it on your confirmation page and do not prefill it from the row or the mail, or a reader who clicks straight through confirms the squatter's address again. A re-application on a row that is still unconfirmed mails a fresh confirmation token with the payout address on file, so the real owner can see what someone typed. With no hook wired nothing can be confirmed, and approve() refuses every new signup.
- Re-applications are limited per address: by default 5 in any 24 hours (config reapplyLimit and reapplyWindowHours), counted on the affiliate's own row in your store. Past the limit apply() answers 429 with retryAfterSeconds, sends no mail and rotates no token, so the newest confirmation link already in the inbox keeps working. A new address is not limited by this, so it does not stop someone applying with many different addresses; put your app's own per-IP limit in front of the endpoint for that.
- A re-application does not echo the code to whoever posted the form. apply() answers 200 with reapplied:true and hands the code to the notify hook you pass, addressed to the email on file. With no hook wired, nothing is sent and the response says delivered:false.
- Payouts are NOT automated. recordConversion() writes a ledger row marked pending; paying it needs a provider (Stripe Connect, PayPal) and is a deliberate manual step until you have chosen one.
- Approval, payable, paid and reversed are moved by approve()/setAffiliateStatus(), markPayable(), markPaid() and reverse(). Each needs a named actor, refuses an illegal move by name (a paid commission cannot go back to pending; a reversal is final), and writes one row to affiliate_audit with the actor, the state before and the state after. What it does not do: decide WHEN. Your admin screen calls approve(), a job you schedule calls markPayable() once your refund window has run, your payout run calls markPaid(), and your refund webhook calls reverse(). Reversing a paid commission records the clawback; it does not get the money back. The store must apply each move and its audit row in one statement that checks the old state, as sql/affiliate.sql shows, or two refunds racing can both land.
- NO ORDER ID, NO COMMISSION. recordConversion() refuses a sale whose orderId is missing, blank or whitespace, reason 'no-order-id', and writes nothing. The order id is the duplicate key: a blank one used to make every later sale for that affiliate look like a retry of the first, so it was acked and never recorded. Pass the payment provider's id for the charge (a Stripe payment_intent id, for example).
- Attribution is last-click within the window, which is the common default but IS a business decision: say so on your affiliate terms page rather than leaving it implied.
- NO CLICK TIME, NO COMMISSION. recordConversion() refuses a sale that arrives without a referredAt, reason 'no-referral-time', rather than guessing an interval: both fallbacks are wrong, since the affiliate's signup date measures how long the AFFILIATE has existed and 'now' means the window never binds again. If you are wiring this up by hand, pass the referredAt that referral() gives you or nothing will ever record.
- The click time comes from a COOKIE. Written by attachReferral() in the browser, it is client-side and a buyer can rewrite it to look recent, which keeps an old referral earning. To close that, call signReferral(code, { secret }) on your server when a ?ref= link is followed, set its value as the cookie (HttpOnly if you can), pass that value to recordConversion() as referralToken, and set config.referralSecret. A rewritten time then fails the signature ('bad-referral-signature'), and a sale with no token is refused ('unsigned-referral'). Do not also call attachReferral() under the same cookie name, or its unsigned value replaces the signed one. With no referralSecret the signature is not checked, so the forgery stays possible: a bounded loss, since it can only extend one referral's own window.
What lands in your project
vanilla
- vanilla/affiliate.js
attachReferral() captures ?ref= into a bounded cookie AND stamps the click time into it; referral() reads back {code, referredAt} and referralCode() still returns just the code; affiliateLink(code) builds the share URL. Send BOTH values to your conversion endpoint: referredAt is what bounds the attribution window, and recordConversion() refuses a sale it cannot date. Framework-free, so a React page can call these directly.
node
- node/affiliate-api.js
Express/Fastify-agnostic handlers: apply(), me(), recordConversion(), signReferral()/verifyReferral() for a server-signed click time, and the state moves approve(), setAffiliateStatus(), markPayable(), markPaid() and reverse(). Pure functions over a store you inject, so it drops onto any backend. apply() returns a dashboardToken once and stores only its hash; me() needs that token as well as the code. Pass a notify hook to apply(): it mails the confirmation token that verifyEmail() takes, and on a re-application it mails the code to the stored address.
sql
- sql/affiliate.sql
affiliates + affiliate_conversions + affiliate_audit. The unique index on (affiliate_id, order_id) is what makes recordConversion idempotent under webhook retries.
What you supply
- ratePercent: commission percent (default 30)
- windowDays: attribution window in days, measured from the referral CLICK and inclusive at the boundary (default 30, matching AFFILIATE_COOKIE_DAYS). A sale past it earns nothing, reason 'outside-window'.
- cookieName: referral cookie (default wb_ref)
- referralSecret: server-only HMAC key made of random hex characters, at least 64 of them, such as the output of crypto.randomBytes() turned into hex (no default). A repeated letter, a passphrase, hex-encoded text or a repeated pattern is refused as weak-referral-secret, whatever its length. Set it and recordConversion() takes the code and click time only from a referralToken that signReferral() made with it, so a buyer cannot rewrite the click time in their cookie. Unset, the browser-written click time is trusted as before.
Get it
Download the Playground See pricing
A feature of the Vibe Coder Playground.
Questions
- Is Affiliate and referral tracking audited?
- It was audited on 2026-09-29, and the verdict was not a clean pass. 5 findings have been fixed since then, and the verdict stands until the block is audited again.
- What do I still have to do myself?
- The referral code is public, because it sits in every share link, so it cannot unlock earnings. me() refuses a bare code with a 401 and answers only when the caller also sends the dashboard token apply() returned at signup. Only a hash of that token is stored. Your dashboard page must keep the token and send it in a header. This holds until your app has real sessions; then check the session instead. A lost token cannot be recovered from the database, and this block ships no reset flow.
- How do I get this?
- It is a feature of the Vibe Coder Playground. Download the Playground, and see the pricing page for what each plan includes.
All Playground features · Free code blocks · Learn to build from zero · The coding guide