diff --git a/package-lock.json b/package-lock.json index 056ca9c..2093415 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1761,6 +1761,18 @@ "node": ">= 0.8" } }, + "node_modules/dotenv": { + "version": "17.3.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz", + "integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -3402,6 +3414,7 @@ "@affitor/recipes": "^0.1.0", "@inquirer/prompts": "^7.5.0", "commander": "^13.1.0", + "dotenv": "17.3.1", "open": "^10.1.0", "picocolors": "^1.1.1" }, @@ -3419,7 +3432,7 @@ }, "packages/mcp": { "name": "@affitor/mcp", - "version": "0.2.1", + "version": "0.2.2", "license": "MIT", "dependencies": { "@affitor/recipes": "^0.1.0", diff --git a/packages/cli/README.md b/packages/cli/README.md index 516385f..70c8fd3 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -111,10 +111,10 @@ It runs the **detect → wire → inject → verify** flow: 1. **Detect** — your framework (`next-app`, `next-pages`, `fastify`, `express`, `node`) and payment provider (Stripe, …). 2. **Wire** — installs `@affitor/sdk`, injects `` browser tracking, scaffolds the server client, and persists `AFFITOR_API_KEY` into `.env.local`/`.env`. -3. **Inject** — locates your Stripe webhook and adds the `affitor.trackSale` call (shown as a diff; non-Stripe stacks and unrecognized webhooks get the exact recipe printed instead — payment code is never auto-edited blindly). +3. **Review sale tracking** — if the program has a Stripe account bound in Affitor, the webhook stays unchanged to avoid a second sale path. When the runtime key or Connect state is uncertain, the CLI asks whether to keep the existing webhook unchanged (default Yes). Only choose No after confirming the runtime program key and ruling out current/shared-account/delayed Connect sales; a separate diff approval is required before adding `affitor.trackSale`. Unknown status never recommends removing an existing sale call. `--yes`, `--no-interactive` and `--json` leave Stripe webhooks unchanged when Connect cannot be ruled out. A conflicting runtime API key always requires manual review. Non-Stripe stacks and unrecognized webhooks get a recipe to review and add manually. 4. **Verify** — fires the synthetic click → lead → sale chain, then **polls readiness until `integration_verified`** (or reports the blocking gate + next action). -It is **idempotent** — re-running skips work already done (existing env key, sale call already present) and never overwrites a different `AFFITOR_API_KEY`. +It is **idempotent** — re-running skips work already done (existing env key, sale call already present) and never overwrites a different `AFFITOR_API_KEY`. The CLI trusts status only when the inherited process key and standard env layers declare one distinct usable key matching the checked key. It parses dotenv syntax (including colon assignments and quoted multiline values) without evaluating or expanding it. Duplicate assignments, conflicting keys across `.env`, `.env.local`, and `.env.{production,development,test}[.local]`, unreadable/nonregular files, or any other root `.env*` file make the runtime key uncertain. This includes custom modes and templates: the CLI does not infer how they are loaded. In interactive mode it asks and defaults to keeping the existing snippet; unattended runs keep it unchanged. Ambiguous env files are never overwritten. If no runtime key exists and every standard layer is readable, the normal env initialization can still add the explicit program key. | Flag | Description | |---|---| diff --git a/packages/cli/package.json b/packages/cli/package.json index d6b6b76..7212a5b 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,7 +1,7 @@ { "name": "affitor", "version": "0.4.4", - "description": "CLI-native affiliate tracking. Connect Stripe, track commissions, manage partners — all from your terminal.", + "description": "CLI-native affiliate tracking. Connect Stripe, track commissions, manage partners \u2014 all from your terminal.", "type": "module", "bin": { "affitor": "./dist/cli.js" @@ -44,7 +44,8 @@ "@inquirer/prompts": "^7.5.0", "picocolors": "^1.1.1", "open": "^10.1.0", - "@affitor/recipes": "^0.1.0" + "@affitor/recipes": "^0.1.0", + "dotenv": "17.3.1" }, "devDependencies": { "typescript": "^5.7.0", diff --git a/packages/cli/src/commands/onboard.ts b/packages/cli/src/commands/onboard.ts index c07b95f..3a6741e 100644 --- a/packages/cli/src/commands/onboard.ts +++ b/packages/cli/src/commands/onboard.ts @@ -9,9 +9,10 @@ import { AffitorAPI, APIError, NetworkError } from "../lib/api-client.js"; import { resolveApiKey } from "../lib/config.js"; import { confirmAction } from "../lib/prompts.js"; import { detectStack, type Framework } from "../lib/stack-detect.js"; -import { detectPaymentProvider } from "../lib/server-tracking.js"; +import { detectPaymentProvider, serverTrackingSnippets } from "../lib/server-tracking.js"; import { detectStripeWebhook } from "../lib/webhook-detect.js"; import { injectStripeTrackSale } from "../lib/inject.js"; +import { inspectProjectEnvironment } from "../lib/project-env.js"; import { runInstallWizard } from "../lib/wizard.js"; import { DEFAULT_API_URL, type CLIFlags, type ReadinessResult, type TestChainStatus } from "../types.js"; @@ -96,11 +97,20 @@ export async function runOnboard(opts: OnboardOpts, flags: CLIFlags) { ]); } + // Does Affitor already record this program's Stripe payments (Connect)? Read once, before the + // wizard, so neither the wizard nor the sale step advises a second, double-counting trackSale. + const stripeAccountBound = provider === "stripe" + ? await stripeBindingFor(api, cwd, apiKey, flags.json) + : undefined; + // ── (c) Browser tracking — reuse init's wizard (install @affitor/sdk + // inject via diff-preview+confirm + scaffold lib/affitor.ts). // Skipped in --json mode (the wizard is interactive/printed output). ── if (!flags.json) { - await runInstallWizard({ cwd, programId: "", apiUrl, autoConfirm }); + await runInstallWizard({ + cwd, programId: "", apiUrl, autoConfirm, + stripeRecordsSales: provider === "stripe" ? (stripeAccountBound === true ? true : "unknown") : undefined, + }); steps.push({ step: "browser_tracking", status: "ok", detail: "via install wizard" }); } else { steps.push({ step: "browser_tracking", status: "skipped", detail: "json mode" }); @@ -114,6 +124,7 @@ export async function runOnboard(opts: OnboardOpts, flags: CLIFlags) { interactive, autoConfirm, json: flags.json, + stripeAccountBound, }); steps.push(saleStep); @@ -166,6 +177,48 @@ interface WireSaleArgs { interactive: boolean; autoConfirm: boolean; json: boolean; + /** A Stripe account is bound to the program in Affitor; undefined when it could not be read. */ + stripeAccountBound?: boolean; +} + +/** + * Does Affitor record this program's Stripe payments through Connect? Connect credits a sale when + * the program is bound to the event's Stripe account, whatever the connection status says + * (pending_verification still records), so `GET /v1/cli/status` answers with + * `stripe_account_bound`. Not `stripe_connected`: it is false while pending, and before CMS + * v3.16.91 it was true for any Server API program. undefined when the call fails or the field + * is missing, so the caller asks instead of guessing. + */ +export async function readStripeAccountBound(api: Pick): Promise { + try { + const status = await api.getStatus(); + // A disconnected/shared account can still deliver earlier events. Only true is decisive; + // false describes the current binding, not the absence of a Connect sale writer. + return status?.stripe_account_bound === true ? true : undefined; + } catch { + return undefined; + } +} + +/** + * The binding for the program whose key the app will run with. The status call answers for the + * key passed to onboard; when the env file already holds a different key, the webhook runs as that + * other program, so the answer does not apply: unknown. + */ +async function stripeBindingFor( + api: Pick, + cwd: string, + apiKey: string, + json: boolean, +): Promise { + const env = inspectProjectEnvironment(cwd, apiKey); + if (!env.certain) { + if (!json) { + logger.warn(`The app runtime key is uncertain (${env.reason}); review all env layers and the program before changing sale tracking.`); + } + return undefined; + } + return readStripeAccountBound(api); } /** @@ -177,7 +230,7 @@ interface WireSaleArgs { * - no webhook → PRINT the full recipe. * NEVER auto-edits when the structure isn't cleanly recognized. */ -async function wireServerSale(args: WireSaleArgs): Promise { +export async function wireServerSale(args: WireSaleArgs): Promise { const { cwd, framework, provider, interactive, autoConfirm, json } = args; // Only Stripe has the auto-edit path (the recipe's sale snippet is keyed to @@ -196,6 +249,29 @@ async function wireServerSale(args: WireSaleArgs): Promise { const hook = detectStripeWebhook(cwd, framework); + // A connected Stripe already reports every payment to Affitor, so a trackSale call in the + // webhook would record the same payment a second time (a subscription's first payment as two + // sales). Never add one then; when the connection is unknown, ask, and without a person to + // ask, change nothing. + let connected: boolean | undefined = args.stripeAccountBound === true ? true : undefined; + if (connected === undefined && interactive && !autoConfirm && !json) { + const keep = await confirmAction( + "Keep the existing webhook unchanged? Choose No only after confirming this app's runtime program key and ruling out current Stripe Connect sales, shared accounts and delayed events after disconnect.", + ); + if (keep) return skipSaleForConnect({ cwd, framework, recipe, hook, json, unknown: true }); + connected = false; + } + if (connected !== false) { + return skipSaleForConnect({ cwd, framework, recipe, hook, json, unknown: connected === undefined }); + } + + if (!json) { + logger.titledBox("Manual tracking: handle refunds too", [ + "", " On refund, reverse the commission using the same id you passed to trackSale:", + ...serverTrackingSnippets("stripe").refund.split("\n").map(line => ` ${line}`), "", + ]); + } + if (!hook) { if (!json) { printRecipe(recipe, null, "Stripe sale (no webhook found — add this where you verify webhooks)"); @@ -271,6 +347,122 @@ async function wireServerSale(args: WireSaleArgs): Promise { return { step: "server_sale", status: "ok", detail: hook.file }; } +/** Find call tokens outside comments/literals; template interpolation is executable code. */ +export function callsTrackSale(source: string): boolean { + let i = 0; + let found = false; + function quoted(quote: string) { + i++; + while (i < source.length) { + if (source[i] === "\\") { i += 2; continue; } + if (source[i++] === quote) break; + } + } + function template() { + i++; + while (i < source.length) { + if (source[i] === "\\") { i += 2; continue; } + if (source[i] === "`") { i++; return; } + if (source[i] === "$" && source[i + 1] === "{") { i += 2; code(true); } + else i++; + } + } + function code(interpolation = false) { + let previous = ""; + let depth = 0; + while (i < source.length) { + const c = source[i]; + if (/\s/.test(c)) { i++; continue; } + if (source.startsWith("//", i)) { + const end = source.indexOf("\n", i + 2); i = end < 0 ? source.length : end; continue; + } + if (source.startsWith("/*", i)) { + const end = source.indexOf("*/", i + 2); i = end < 0 ? source.length : end + 2; continue; + } + if (c === "'" || c === '"') { quoted(c); previous = "literal"; continue; } + if (c === "`") { template(); previous = "literal"; continue; } + // A regex literal can contain call-like text too. Distinguish it from division + // at expression starts; slash escapes and character classes belong to the literal. + if (c === "/" && (!previous || ["=", "(", ":", ",", "[", "!", "return", "=>"].includes(previous))) { + i++; let inClass = false; + while (i < source.length) { + if (source[i] === "\\") { i += 2; continue; } + if (source[i] === "[") inClass = true; + if (source[i] === "]") inClass = false; + if (source[i++] === "/" && !inClass) break; + } + previous = "literal"; continue; + } + if (/[A-Za-z_$]/.test(c)) { + const start = i++; + while (i < source.length && /[\w$]/.test(source[i])) i++; + previous = source.slice(start, i); continue; + } + if (source.startsWith("=>", i)) { previous = "=>"; i += 2; continue; } + if (c === "(" && previous === "trackSale") found = true; + if (c === "{") depth++; + if (c === "}") { if (interpolation && depth === 0) { i++; return; } depth--; } + previous = c; i++; + } + } + code(); + return found; +} + +/** + * Stripe connected (or unknown with no one to ask): print the Connect recipe (checkout metadata + * only) and leave the webhook alone. A webhook that already calls trackSale is pointed out, + * since with Stripe connected it counts each payment twice. + */ +function skipSaleForConnect(args: { + cwd: string; + framework: Framework; + /** The s2s recipe, printed when the connection is unknown. */ + recipe: ReturnType; + hook: { file: string; line: number; handlerHint: string } | null; + json: boolean; + unknown: boolean; +}): OnboardStep { + const { cwd, framework, recipe, hook, json, unknown } = args; + let tracksSale = false; + if (hook) { + try { + tracksSale = callsTrackSale(readFileSync(join(cwd, hook.file), "utf8")); + } catch { + /* unreadable: nothing to point out */ + } + } + + if (!json) { + if (unknown) { + logger.warn("Couldn't tell whether Stripe is connected, so your webhook was left unchanged."); + } + if (tracksSale) { + logger.warn( + unknown + ? `${hook!.file} calls trackSale. It was left unchanged; confirm the runtime program and its Connect sale paths before changing this call.` + : `${hook!.file} calls trackSale. With Stripe connected, Affitor already records each payment, so remove that call or every sale counts twice.`, + ); + } + if (unknown) { + printRecipe(recipe, hook, "Keep existing sale tracking; add a call only after confirming the runtime program and ruling out current, shared-account and delayed Connect events"); + } else { + printRecipe( + getRecipe(toRecipeFramework(framework), "stripe", "stripe_connect"), + null, + "Stripe connected: Affitor records the sale", + ); + } + } + + const detail = unknown + ? "stripe connection unknown: webhook unchanged, printed recipe" + : tracksSale + ? `stripe connected: no trackSale added; ${hook!.file} already calls trackSale (double count)` + : "stripe connected: Affitor records the sale, no trackSale added"; + return { step: "server_sale", status: unknown ? "manual" : "skipped", detail }; +} + /** * (e) Always PRINT the metadata-propagation snippet — we never auto-edit the * checkout-session-create call (it can't be located reliably). Plus the sale @@ -327,27 +519,19 @@ function writeApiKeyToEnv( apiKey: string, opts: { autoConfirm: boolean; json: boolean }, ): OnboardStep { - const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; + const env = inspectProjectEnvironment(cwd, apiKey); + const { envName } = env; const envPath = join(cwd, envName); const line = `AFFITOR_API_KEY=${apiKey}`; - - let content = ""; - if (existsSync(envPath)) { - content = readFileSync(envPath, "utf8"); - const existing = content.match(/^AFFITOR_API_KEY=(.*)$/m); - if (existing) { - if (existing[1].trim() === apiKey) { - if (!opts.json) logger.step(`${envName} already has AFFITOR_API_KEY — skipped`); - return { step: "env_key", status: "already", detail: envName }; - } - // Different value present — NEVER overwrite a secret. Print a notice. - if (!opts.json) { - logger.warn(`${envName} already has a different AFFITOR_API_KEY — left unchanged.`); - logger.step(`To use this key instead, set: ${line}`); - } - return { step: "env_key", status: "manual", detail: `${envName}: existing value kept` }; - } + if (!env.certain && env.reason !== "no_runtime_key") { + if (!opts.json) logger.warn("Project env layers are uncertain — resolve them manually. Nothing was changed."); + return { step: "env_key", status: "manual", detail: `env review required: ${env.reason}` }; + } + if (env.hasTargetKey) { + if (!opts.json) logger.step(`${envName} already has AFFITOR_API_KEY — skipped`); + return { step: "env_key", status: "already", detail: envName }; } + const content = existsSync(envPath) ? readFileSync(envPath, "utf8") : ""; // --json (non-interactive auto) mode never edits files — the no-auto-edit // contract. Report it as a manual step (mirrors wireServerSale's json branch) @@ -358,7 +542,7 @@ function writeApiKeyToEnv( logger.newline(); logger.info(` ${format.dim(`Add to ${envName}:`)}`); - logger.info(` ${format.green("+ " + line)}`); + logger.info(` ${format.green("+ AFFITOR_API_KEY=")}`); logger.newline(); const needsNewline = content.length > 0 && !content.endsWith("\n"); diff --git a/packages/cli/src/lib/project-env.ts b/packages/cli/src/lib/project-env.ts new file mode 100644 index 0000000..7011365 --- /dev/null +++ b/packages/cli/src/lib/project-env.ts @@ -0,0 +1,74 @@ +import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { parse } from "dotenv"; + +const ENV_NAMES = [".env", ".env.local", ...["production", "development", "test"].flatMap(mode => [`.env.${mode}`, `.env.${mode}.local`])]; +type Reason = "certain" | "no_runtime_key" | "unknown_layer" | "unreadable_layer" | "duplicate_assignment" | "conflicting_keys"; +export interface ProjectEnvironment { envName: string; hasTargetKey: boolean; certain: boolean; reason: Reason } + +// Only assignment boundaries are shared with the pinned dotenv parser so duplicate +// counting respects quoted multiline values. Values always come from dotenv.parse. +// Grammar from dotenv17.3.1; the required redistribution notice follows. +/* +Copyright (c) 2015, Scott Motte +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +const DOTENV_ASSIGNMENT = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + +export function inspectProjectEnvironment(cwd: string, expectedKey: string): ProjectEnvironment { + const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; + const result = (reason: Reason, hasTargetKey = false): ProjectEnvironment => ({ envName, hasTargetKey, certain: reason === "certain", reason }); + let names: string[]; + try { names = readdirSync(cwd); } catch { return result("unreadable_layer"); } + // No inference about custom loaders, templates or nonstandard runtime modes. + if (names.some(name => name.toLowerCase().startsWith(".env") && !ENV_NAMES.includes(name))) return result("unknown_layer"); + const keys: string[] = []; + if (process.env.AFFITOR_API_KEY !== undefined) keys.push(process.env.AFFITOR_API_KEY); + let hasTargetKey = false; + for (const name of ENV_NAMES) { + let text: string; + try { + const path = join(cwd, name); + const stat = lstatSync(path); + if (!stat.isFile() || stat.isSymbolicLink()) return result("unreadable_layer"); + const bytes = readFileSync(path); + text = bytes.toString("utf8"); + if (!Buffer.from(text, "utf8").equals(bytes)) return result("unreadable_layer"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; + return result("unreadable_layer"); + } + const normalized = text.replace(/\r\n?/g, "\n"); + const assignments = [...normalized.matchAll(DOTENV_ASSIGNMENT)].filter(match => match[1] === "AFFITOR_API_KEY"); + if (assignments.length > 1) return result("duplicate_assignment"); + const values = parse(text); + if (Object.hasOwn(values, "AFFITOR_API_KEY")) { + keys.push(values.AFFITOR_API_KEY); + if (name === envName) hasTargetKey = true; + } + } + if (!keys.length) return result("no_runtime_key"); + if (keys.some(key => !/^[A-Za-z0-9_-]+$/.test(key)) || new Set(keys).size !== 1 || keys[0] !== expectedKey) return result("conflicting_keys", hasTargetKey); + return result("certain", hasTargetKey); +} diff --git a/packages/cli/src/lib/wizard.ts b/packages/cli/src/lib/wizard.ts index 880d602..ab9bd06 100644 --- a/packages/cli/src/lib/wizard.ts +++ b/packages/cli/src/lib/wizard.ts @@ -24,6 +24,8 @@ export interface WizardOptions { programId: string | number; apiUrl: string; autoConfirm: boolean; + /** true: bound now; unknown: onboarding cannot rule out Connect. Both suppress sale advice. */ + stripeRecordsSales?: true | "unknown"; } function rel(cwd: string, p: string): string { @@ -145,6 +147,10 @@ async function setupServerTracking( // If they already verify Stripe webhooks somewhere, point at the exact site // (the trackSale call belongs right after constructEvent). Best-effort hint — // we still print the full snippets below as the canonical reference. + if (provider === "stripe" && opts.stripeRecordsSales) { + printServerSnippets(serverTrackingSnippets(provider), { salesFromStripe: opts.stripeRecordsSales }); + return; + } if (provider === "stripe") { const hook = detectStripeWebhook(opts.cwd, framework); if (hook) { @@ -160,9 +166,17 @@ async function setupServerTracking( printServerSnippets(serverTrackingSnippets(provider)); } -function printServerSnippets(s: TrackingSnippets): void { +function printServerSnippets(s: TrackingSnippets, opts: { salesFromStripe?: true | "unknown" } = {}): void { const lines: string[] = ["", ` ${format.dim("1) At signup — bind the customer (server-side):")}`]; for (const l of s.lead.split("\n")) lines.push(` ${format.cyan(l)}`); + if (opts.salesFromStripe) { + const advice = opts.salesFromStripe === true + ? "2) Stripe is bound in Affitor. Do not add a second trackSale path; it can count a payment twice." + : "2) Stripe sale tracking needs review. Check current, shared-account and delayed Connect events before adding trackSale."; + lines.push("", ` ${format.dim(advice)}`, ""); + logger.titledBox("Track conversions (add to your backend)", lines); + return; + } lines.push("", ` ${format.dim(`2) At purchase — ${s.saleContext}:`)}`); for (const l of s.sale.split("\n")) lines.push(` ${format.cyan(l)}`); lines.push("", ` ${format.dim("3) On refund — reverse the commission:")}`); diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.ts index 6ea32af..59fcd15 100644 --- a/packages/cli/src/types.ts +++ b/packages/cli/src/types.ts @@ -67,6 +67,8 @@ export interface ProgramStatus { dns_verified: boolean; stripe_connected: boolean; stripe_charges_enabled?: boolean; + /** Current Stripe binding only. false does not rule out delayed/shared-account Connect events. */ + stripe_account_bound?: boolean; recent_events: { clicks_24h: number; leads_24h: number; diff --git a/packages/cli/tests/inject-stripe-tracksale.test.ts b/packages/cli/tests/inject-stripe-tracksale.test.ts index 84808e1..0589598 100644 --- a/packages/cli/tests/inject-stripe-tracksale.test.ts +++ b/packages/cli/tests/inject-stripe-tracksale.test.ts @@ -52,10 +52,10 @@ describe("injectStripeTrackSale — injected (clean shape)", () => { expect(saleIdx).toBeLessThan(fulfillIdx); // The sale snippet is wrapped in a `$0/null` guard (M1): the `if` lands at the - // session binding's indentation (6 spaces); the guarded trackSale sits one - // level deeper (8 spaces). + // session binding's indentation (6 spaces); the trackSale sits inside it and + // inside the has-a-key check (10 spaces). expect(r.content).toMatch(/\n {6}if \(session\.amount_total && session\.amount_total > 0\) \{/); - expect(r.content).toMatch(/\n {8}await affitor\.trackSale\(\{/); + expect(r.content).toMatch(/\n {10}await affitor\.trackSale\(\{/); }); it("reads the customer key the metadata step writes (B1: affitor_customer_key, not client_reference_id)", () => { @@ -65,8 +65,9 @@ describe("injectStripeTrackSale — injected (clean shape)", () => { const r = injectStripeTrackSale(CLEAN_FASTIFY, { saleSnippet: SALE_SNIPPET }); expect(r.status).toBe("injected"); expect(r.content).toContain( - "customerExternalId: session.metadata?.affitor_customer_key ?? session.client_reference_id", + "const affitorKey = session.metadata?.affitor_customer_key ?? session.client_reference_id;", ); + expect(r.content).toContain("customerExternalId: affitorKey,"); // It must NOT read client_reference_id alone (the old, broken contract). expect(r.content).not.toMatch(/customerExternalId:\s*session\.client_reference_id,/); }); @@ -103,9 +104,9 @@ describe("injectStripeTrackSale — injected (clean shape)", () => { it("respects an explicit indent override", () => { const r = injectStripeTrackSale(CLEAN_FASTIFY, { saleSnippet: SALE_SNIPPET, indent: "" }); expect(r.status).toBe("injected"); - // indent "" → the guard `if` sits at column 0; the guarded trackSale at 2 spaces. + // indent "" → the guard `if` sits at column 0; the trackSale inside both checks at 4 spaces. expect(r.content).toMatch(/\nif \(session\.amount_total && session\.amount_total > 0\) \{/); - expect(r.content).toMatch(/\n {2}await affitor\.trackSale\(\{/); + expect(r.content).toMatch(/\n {4}await affitor\.trackSale\(\{/); }); }); diff --git a/packages/cli/tests/onboard-stripe-connected.test.ts b/packages/cli/tests/onboard-stripe-connected.test.ts new file mode 100644 index 0000000..3517440 --- /dev/null +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -0,0 +1,535 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { chmodSync, mkdtempSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +const confirmAction = vi.fn<(message: string) => Promise>(); +vi.mock("../src/lib/prompts.js", () => ({ confirmAction: (m: string) => confirmAction(m) })); + +// runOnboard's collaborators: the wizard (records what it was told) and the API (status as given). +const wizardCalls: Array> = []; +vi.mock("../src/lib/wizard.js", () => ({ + runInstallWizard: async (opts: Record) => { + wizardCalls.push(opts); + }, +})); +const apiState: { status: unknown } = { status: {} }; +vi.mock("../src/lib/api-client.js", async (orig) => { + const real = await orig(); + class FakeAPI { + async getStatus() { + if (apiState.status instanceof Error) throw apiState.status; + return apiState.status; + } + async runVerificationChain() { + return {}; + } + async getReadiness() { + return { integration_verified: true }; + } + } + return { ...real, AffitorAPI: FakeAPI }; +}); + +const { callsTrackSale, readStripeAccountBound, runOnboard, wireServerSale } = await import("../src/commands/onboard"); + +/** + * Report 2026-10-17 (onboard trackSale double count): with the program's Stripe connected, + * Affitor already records each payment, so `affitor onboard` must not add a trackSale call + * (a subscription's first payment was recorded twice). Unknown connection: ask, and with + * nobody to ask, change nothing. + */ + +const WEBHOOK = `import Fastify from 'fastify'; +import Stripe from 'stripe'; + +const stripe = new Stripe(process.env.STRIPE_KEY!); +const app = Fastify(); + +app.post('/webhooks/stripe', async (req, reply) => { + const sig = req.headers['stripe-signature'] as string; + const event = stripe.webhooks.constructEvent(req.rawBody, sig, secret); + + switch (event.type) { + case 'checkout.session.completed': { + const session = event.data.object as Stripe.Checkout.Session; + await fulfill(session); + break; + } + } + + reply.send({ received: true }); +}); +`; +const HOOK_FILE = join("src", "routes", "webhooks.ts"); + +const dirs: string[] = []; +function project(webhook = WEBHOOK): string { + const dir = mkdtempSync(join(tmpdir(), "affitor-onboard-")); + const full = join(dir, HOOK_FILE); + mkdirSync(dirname(full), { recursive: true }); + writeFileSync(full, webhook); + dirs.push(dir); + return dir; +} +const webhookOf = (dir: string) => readFileSync(join(dir, HOOK_FILE), "utf8"); + +function wire(cwd: string, over: Partial[0]> = {}) { + return wireServerSale({ + cwd, + framework: "fastify", + provider: "stripe", + interactive: false, + autoConfirm: true, + json: false, + ...over, + }); +} + +beforeEach(() => { + vi.stubEnv("AFFITOR_API_KEY", undefined); + confirmAction.mockReset(); + wizardCalls.length = 0; + apiState.status = {}; + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); +}); +afterEach(() => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + process.exitCode = undefined; + while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); +}); + +describe("wireServerSale — Stripe connected in Affitor", () => { + it("adds no trackSale and leaves the webhook unchanged, even with --yes", async () => { + const dir = project(); + const step = await wire(dir, { stripeAccountBound: true }); + expect(step).toMatchObject({ step: "server_sale", status: "skipped" }); + expect(step.detail).toContain("stripe connected"); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it("points out a webhook that already calls trackSale (it counts each payment twice)", async () => { + const wired = WEBHOOK.replace("await fulfill(session);", "await affitor.trackSale({ customerExternalId: 'u', amount: 1, invoiceId: session.id });"); + const dir = project(wired); + const step = await wire(dir, { stripeAccountBound: true }); + expect(step.status).toBe("skipped"); + expect(step.detail).toContain("already calls trackSale"); + expect(webhookOf(dir)).toBe(wired); + }); +}); + +describe("wireServerSale — Stripe not connected", () => { + it("a false current binding cannot rule out delayed/shared-account events (--yes leaves the webhook alone)", async () => { + const dir = project(); + const step = await wire(dir, { stripeAccountBound: false }); + expect(step.status).toBe("manual"); + expect(webhookOf(dir)).toBe(WEBHOOK); + }); +}); + +describe("wireServerSale — connection unknown", () => { + it("with --yes (nobody to ask): webhook unchanged, reported as manual", async () => { + const dir = project(); + const step = await wire(dir, { stripeAccountBound: undefined }); + expect(step.status).toBe("manual"); + expect(step.detail).toContain("unknown"); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it("in --json mode: webhook unchanged, nobody asked", async () => { + const dir = project(); + const step = await wire(dir, { stripeAccountBound: undefined, json: true, autoConfirm: false, interactive: true }); + expect(step.status).toBe("manual"); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it("interactive, keep default: unknown remains manual and no trackSale added", async () => { + const dir = project(); + confirmAction.mockResolvedValueOnce(true); + const step = await wire(dir, { stripeAccountBound: undefined, interactive: true, autoConfirm: false }); + expect(confirmAction).toHaveBeenCalledTimes(1); + expect(confirmAction.mock.calls[0][0]).toContain("Keep the existing webhook unchanged?"); + expect(confirmAction.mock.calls[0][0]).toContain("delayed events after disconnect"); + expect(step.status).toBe("manual"); + expect(webhookOf(dir)).toBe(WEBHOOK); + }); + + it("interactive, answer no: shows the diff and adds the call once confirmed", async () => { + const dir = project(); + confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + const step = await wire(dir, { stripeAccountBound: undefined, interactive: true, autoConfirm: false }); + expect(confirmAction).toHaveBeenCalledTimes(2); + expect(step.status).toBe("ok"); + expect(webhookOf(dir)).toContain("await affitor.trackSale({"); + }); +}); + +describe("readStripeAccountBound", () => { + const api = (status: unknown) => ({ getStatus: async () => status as never }); + + it("reads stripe_account_bound from GET /v1/cli/status", async () => { + expect(await readStripeAccountBound(api({ stripe_account_bound: true, stripe_connected: false }))).toBe(true); + expect(await readStripeAccountBound(api({ stripe_account_bound: false }))).toBeUndefined(); + }); + + it("an older CMS that only sends stripe_connected is unknown, never trusted (it meant Server API mode once)", async () => { + expect(await readStripeAccountBound(api({ stripe_connected: true }))).toBeUndefined(); + expect(await readStripeAccountBound(api({ stripe_connected: false }))).toBeUndefined(); + }); + + it("is undefined when the call fails", async () => { + expect( + await readStripeAccountBound({ + getStatus: async () => { + throw new Error("network"); + }, + }), + ).toBeUndefined(); + }); +}); + +describe("callsTrackSale", () => { + it("finds a real call, not a comment", () => { + expect(callsTrackSale("await affitor.trackSale({ invoiceId })")).toBe(true); + expect(callsTrackSale("// trackSale is documented elsewhere")).toBe(false); + expect(callsTrackSale(" // await affitor.trackSale({})")).toBe(false); + + }); + + it.each([ + '/* example:\nawait affitor.trackSale({});\n*/', + 'const example = "await affitor.trackSale({})";', + "const example = 'trackSale({})';", + 'const example = `trackSale({})`;', + 'const example = /trackSale(foo)/;', + 'const example = () => /trackSale(foo)/;', + 'const example = `escaped \\` trackSale({})`;', + ])("ignores comment/string examples: %s", async source => { + expect(callsTrackSale(source)).toBe(false); + const dir = project(WEBHOOK.replace("await fulfill(session);", source)); + expect((await wire(dir, { stripeAccountBound: true })).detail).not.toContain("already calls trackSale"); + }); + + it.each([ + '/* docs */ await affitor.trackSale /* review */ ({})', + 'const message = `paid ${await affitor.trackSale({})}`;', + 'const message = `nested ${{value: `call ${affitor.trackSale({})}`}}`;', + 'const rate = total / count; await affitor.trackSale({});', + ])("retains real calls: %s", source => expect(callsTrackSale(source)).toBe(true)); + + it("a comment mentioning trackSale is not reported as a double count", async () => { + const commented = WEBHOOK.replace("await fulfill(session);", "// trackSale is documented elsewhere\n await fulfill(session);"); + const dir = project(commented); + const step = await wire(dir, { stripeAccountBound: true }); + expect(step.detail).not.toContain("already calls trackSale"); + }); +}); + +const FLAGS = { json: false, noInteractive: false, autoConfirm: false, quiet: false, verbose: false, apiUrl: "http://test.local" }; + +/** A Fastify + Stripe app the detectors recognise, with the webhook above. */ +function app(env: string | undefined = "AFFITOR_API_KEY=key_a\n"): string { + const dir = project(); + writeFileSync(join(dir, "package.json"), JSON.stringify({ dependencies: { fastify: "^4.0.0", stripe: "^14.0.0" } })); + if (env !== undefined) writeFileSync(join(dir, ".env"), env); + return dir; +} + +async function onboardIn(dir: string, opts: Record = {}, flags: Partial = {}) { + const cwd = process.cwd(); + process.chdir(dir); + try { + await runOnboard({ apiKey: "key_a", yes: true, ...opts }, { ...FLAGS, ...flags }); + } finally { + process.chdir(cwd); + } +} + +describe("runOnboard reads the binding and passes it on", () => { + it("bound: webhook unchanged, and the wizard is told sales come from Stripe", async () => { + apiState.status = { stripe_account_bound: true, stripe_connected: false }; + const dir = app(); + await onboardIn(dir); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(wizardCalls[0]).toMatchObject({ stripeRecordsSales: true }); + }); + + it('connected interactive run does not ask a Connect or injection question', async () => { + apiState.status = { stripe_account_bound: true, stripe_connected: false }; + const dir = app(); + confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(confirmAction).not.toHaveBeenCalled(); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(wizardCalls[0].stripeRecordsSales).toBe(true); + }); + + it('connected JSON run reports skipped, rather than unknown/manual', async () => { + apiState.status = { stripe_account_bound: true }; + const dir = app(); + await onboardIn(dir, { yes: false }, { json: true }); + const summary = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)![0]); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'server_sale', status: 'skipped' })); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it("not bound: --yes leaves the webhook alone and the wizard gets unknown", async () => { + apiState.status = { stripe_account_bound: false }; + const dir = app(); + await onboardIn(dir); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(wizardCalls[0]).toMatchObject({ stripeRecordsSales: "unknown" }); + }); + + it("an older CMS (stripe_connected only): unknown, so --yes leaves the webhook alone", async () => { + apiState.status = { stripe_connected: true }; + const dir = app(); + await onboardIn(dir); + expect(webhookOf(dir)).toBe(WEBHOOK); + }); + + it("the env file holds another program's key: the answer is not trusted, webhook unchanged", async () => { + apiState.status = { stripe_account_bound: false }; + const dir = app("AFFITOR_API_KEY=key_b\n"); + await onboardIn(dir); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(readFileSync(join(dir, ".env"), "utf8")).toBe("AFFITOR_API_KEY=key_b\n"); + }); + + it("the env file holds the same key: the answer is used", async () => { + apiState.status = { stripe_account_bound: true }; + const dir = app("AFFITOR_API_KEY=key_a\n"); + await onboardIn(dir); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(wizardCalls[0]).toMatchObject({ stripeRecordsSales: true }); + }); + + it.each([{ noInteractive: true }, { json: true }])('false stays manual with flags %j', async (flags) => { + apiState.status = { stripe_account_bound: false }; + const dir = app(); + await onboardIn(dir, { yes: false }, flags); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it('interactive false asks about possible Connect events before a diff can be confirmed', async () => { + apiState.status = { stripe_account_bound: false }; + const dir = app(); + confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(confirmAction.mock.calls[0][0]).toContain('shared account'); + expect(confirmAction).toHaveBeenCalledTimes(2); + expect(webhookOf(dir)).toContain('await affitor.trackSale({'); + }); + + it.each(['AFFITOR_API_KEY=key_b\n', 'export AFFITOR_API_KEY = key_b\n'])('key mismatch stays manual even interactively (%s)', async (env) => { + apiState.status = { stripe_account_bound: false }; + const dir = app(env); + confirmAction.mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); + expect(confirmAction).toHaveBeenCalledTimes(1); + }); + + it.each([ + { json: true }, { noInteractive: true }, { autoConfirm: true }, {}, + ])('duplicate env assignments fail closed through runOnboard (%j)', async flags => { + const env = 'AFFITOR_API_KEY=key_a\nexport AFFITOR_API_KEY = key_b\n'; + const dir = app(env); + apiState.status = { stripe_account_bound: true }; + confirmAction.mockResolvedValue(true); + await onboardIn(dir, { yes: false }, flags); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); + expect(confirmAction).toHaveBeenCalledTimes(Object.keys(flags).length ? 0 : 1); + if (flags.json) { + const summary = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)![0]); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'server_sale', status: 'manual' })); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'env_key', status: 'manual' })); + } else { + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + } + }); + + it('prints manual refund advice after confirming the manual sale path', async () => { + const dir = app(); + apiState.status = { stripe_account_bound: false }; + confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(webhookOf(dir)).toContain('await affitor.trackSale({'); + const output = vi.mocked(console.log).mock.calls.flat().join('\n'); + expect(output).toContain('trackRefund'); + expect(output).toContain('same id you passed to trackSale'); + }); + + it.each(['production', 'development', 'test'])('mode-specific %s override forces manual through runOnboard', async mode => { + const dir = app(); + writeFileSync(join(dir, 'package.json'), JSON.stringify({ dependencies: { next: '^15.0.0', stripe: '^14.0.0' } })); + const local = 'AFFITOR_API_KEY=key_a\n'; + const override = 'AFFITOR_API_KEY=key_b\n'; + writeFileSync(join(dir, '.env.local'), local); + writeFileSync(join(dir, `.env.${mode}.local`), override); + apiState.status = { stripe_account_bound: true }; + await onboardIn(dir, { yes: false }, { json: true }); + const summary = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)![0]); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'server_sale', status: 'manual' })); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'env_key', status: 'manual' })); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(readFileSync(join(dir, '.env.local'), 'utf8')).toBe(local); + expect(readFileSync(join(dir, `.env.${mode}.local`), 'utf8')).toBe(override); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it.each(['.env', '.env.local', '.env.production', '.env.production.local', '.env.development', '.env.development.local', '.env.test', '.env.test.local'])("all standard layers are checked interactively: %s", async layer => { + const dir = app(); + const env = 'AFFITOR_API_KEY=key_b\n'; + writeFileSync(join(dir, layer), env); + apiState.status = { stripe_account_bound: true }; + confirmAction.mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + expect(confirmAction).toHaveBeenCalledTimes(1); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(readFileSync(join(dir, layer), 'utf8')).toBe(env); + const output = vi.mocked(console.log).mock.calls.flat().join('\n'); + expect(output).toContain('env layers'); + }); + + it('matching quoted values across mode layers still use the checked binding', async () => { + const dir = app(); + writeFileSync(join(dir, '.env.local'), 'AFFITOR_API_KEY="key_a"\n'); + writeFileSync(join(dir, '.env.production.local'), "export AFFITOR_API_KEY='key_a'\n"); + apiState.status = { stripe_account_bound: true }; + await onboardIn(dir, { yes: false }, { json: true }); + const summary = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)![0]); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'server_sale', status: 'skipped' })); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'env_key', status: 'already' })); + }); + + it('colon override asks and defaults to keeping an existing trackSale snippet', async () => { + const dir = app(); + const wired = WEBHOOK.replace('await fulfill(session);', 'await affitor.trackSale({ invoiceId: session.id });'); + writeFileSync(join(dir, HOOK_FILE), wired); + writeFileSync(join(dir, '.env.production.local'), 'AFFITOR_API_KEY: key_b\n'); + apiState.status = { stripe_account_bound: true }; + confirmAction.mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + expect(confirmAction).toHaveBeenCalledTimes(1); + expect(webhookOf(dir)).toBe(wired); + const output = vi.mocked(console.log).mock.calls.flat().join('\n'); + expect(output).not.toContain('remove that call'); + expect(output).toContain('left unchanged'); + }); + + it('key-looking text inside a multiline value is not a runtime assignment', async () => { + const dir = app('OTHER="begin\nAFFITOR_API_KEY=key_a\nend"\n'); + apiState.status = { stripe_account_bound: true }; + confirmAction.mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + expect(confirmAction).toHaveBeenCalledTimes(1); + expect(webhookOf(dir)).toBe(WEBHOOK); + }); + + it('a real colon key outside another multiline value is recognized without a false duplicate', async () => { + const dir = app('OTHER="begin\nAFFITOR_API_KEY=key_b\nend"\nAFFITOR_API_KEY: key_a\n'); + apiState.status = { stripe_account_bound: true }; + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe(true); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it.each(['missing', 'unknown', 'unreadable'])('uncertain %s env asks once and keeps the webhook', async state => { + const dir = app(); + if (state === 'missing') unlinkSync(join(dir, '.env')); + if (state === 'unknown') writeFileSync(join(dir, '.env.staging'), 'AFFITOR_API_KEY=key_a\n'); + if (state === 'unreadable') chmodSync(join(dir, '.env'), 0); + apiState.status = { stripe_account_bound: true }; + confirmAction.mockResolvedValueOnce(true); + try { + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + expect(confirmAction).toHaveBeenCalledTimes(1); + expect(webhookOf(dir)).toBe(WEBHOOK); + } finally { if (state === 'unreadable') chmodSync(join(dir, '.env'), 0o600); } + }); + + it.each([ + { yes: true, flags: {} }, { yes: false, flags: { json: true } }, + { yes: false, flags: { noInteractive: true } }, { yes: false, flags: { autoConfirm: true } }, + ])('ambiguous colon layers never edit existing sale code unattended (%j)', async ({ yes, flags }) => { + const dir = app(); + const wired = WEBHOOK.replace('await fulfill(session);', 'await affitor.trackSale({ invoiceId: session.id });'); + writeFileSync(join(dir, HOOK_FILE), wired); + const env = 'AFFITOR_API_KEY: key_b\n'; + writeFileSync(join(dir, '.env.production.local'), env); + apiState.status = { stripe_account_bound: true }; + await onboardIn(dir, { yes }, flags); + expect(webhookOf(dir)).toBe(wired); + expect(readFileSync(join(dir, '.env.production.local'), 'utf8')).toBe(env); + expect(readFileSync(join(dir, '.env'), 'utf8')).toBe('AFFITOR_API_KEY=key_a\n'); + expect(confirmAction).not.toHaveBeenCalled(); + if (flags.json) { + const summary = JSON.parse(vi.mocked(console.log).mock.calls.at(-1)![0]); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'server_sale', status: 'manual' })); + expect(summary.steps).toContainEqual(expect.objectContaining({ step: 'env_key', status: 'manual' })); + } + }); + + it('conflicting layers can enter the manual path only after explicit review and a separate diff approval', async () => { + const dir = app(); + writeFileSync(join(dir, '.env.production.local'), 'AFFITOR_API_KEY: key_b\n'); + apiState.status = { stripe_account_bound: true }; + confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + expect(confirmAction).toHaveBeenCalledTimes(2); + expect(confirmAction.mock.calls[0][0]).toContain('runtime program key'); + expect(confirmAction.mock.calls[1][0]).toContain('Apply this change'); + expect(webhookOf(dir)).toContain('await affitor.trackSale({'); + expect(readFileSync(join(dir, '.env.production.local'), 'utf8')).toBe('AFFITOR_API_KEY: key_b\n'); + expect(readFileSync(join(dir, '.env'), 'utf8')).toBe('AFFITOR_API_KEY=key_a\n'); + }); + + it.each([ + 'AFFITOR_API_KEY=key_a\nAFFITOR_API_KEY: key_a\n', + 'AFFITOR_API_KEY=key_a\nAFFITOR_API_KEY: key_b\n', + 'AFFITOR_API_KEY="$OTHER_KEY"\n', + "AFFITOR_API_KEY=`key_a`\nAFFITOR_API_KEY=key_a\n", + ])('ambiguous assignments stay unknown and ask (%s)', async env => { + const dir = app(env); + apiState.status = { stripe_account_bound: true }; + confirmAction.mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + expect(confirmAction).toHaveBeenCalledTimes(1); + expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); + expect(webhookOf(dir)).toBe(WEBHOOK); + }); + + it.each(['key_b', ''])('a runtime process key conflict (%j) cannot be overridden by answering the Connect question', async processKey => { + vi.stubEnv('AFFITOR_API_KEY', processKey); + apiState.status = { stripe_account_bound: false }; + const dir = app(); + confirmAction.mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(confirmAction).toHaveBeenCalledTimes(1); + }); + + it.each([undefined, 'AFFITOR_API_KEY=key_b\n'])('never prints a full program key in the env diff or conflict advice', async (env) => { + const key = 'test_program_key_not_a_real_secret'; + const dir = app(env); + await onboardIn(dir, { apiKey: key }); + const output = vi.mocked(console.log).mock.calls.flat().join('\n'); + expect(output).not.toContain(key); + }); +}); diff --git a/packages/cli/tests/wizard-stripe-mode.test.ts b/packages/cli/tests/wizard-stripe-mode.test.ts new file mode 100644 index 0000000..9e8755d --- /dev/null +++ b/packages/cli/tests/wizard-stripe-mode.test.ts @@ -0,0 +1,47 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { spawnSync } from 'node:child_process'; +import { runInstallWizard } from '../src/lib/wizard'; + +// Exercise the real wizard and generated advice, without installing packages or using the network. +vi.mock('node:child_process', () => ({ spawnSync: vi.fn(() => ({ status: 0 })) })); + +const dirs: string[] = []; +beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(console, 'log').mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); + while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); +}); + +async function advice(stripeRecordsSales?: true | 'unknown') { + const cwd = mkdtempSync(join(tmpdir(), 'affitor-wizard-stripe-')); + dirs.push(cwd); + writeFileSync(join(cwd, 'package.json'), JSON.stringify({ dependencies: { fastify: '4', stripe: '17' } })); + mkdirSync(join(cwd, 'src')); + writeFileSync(join(cwd, 'src', 'server.ts'), "const event = stripe.webhooks.constructEvent(body, signature, secret);\n"); + await runInstallWizard({ cwd, programId: 7, apiUrl: 'http://test.local', autoConfirm: true, stripeRecordsSales }); + expect(spawnSync).toHaveBeenCalledTimes(1); + return vi.mocked(console.log).mock.calls.flat().join('\n'); +} + +describe('the real wizard respects the onboarding Stripe mode', () => { + it.each([true, 'unknown'] as const)('%s prints the lead step without a second sale/refund path', async (mode) => { + const output = await advice(mode); + expect(output).toContain('affitor.trackLead('); + expect(output).not.toContain('affitor.trackSale('); + expect(output).not.toContain('affitor.trackRefund('); + expect(output).not.toContain('→ add trackSale'); + expect(output).toContain(mode === true ? 'Do not add a second trackSale' : 'Stripe sale tracking needs review'); + }); + + it('keeps the existing standalone init wizard advice when no onboarding mode is supplied', async () => { + const output = await advice(); + expect(output).toContain('affitor.trackSale('); + expect(output).toContain('affitor.trackRefund('); + }); +}); diff --git a/packages/recipes/src/index.ts b/packages/recipes/src/index.ts index 00e15c4..22947ef 100644 --- a/packages/recipes/src/index.ts +++ b/packages/recipes/src/index.ts @@ -176,23 +176,35 @@ const SALE_SNIPPET_BODY: Record = { "});", ].join("\n"), paddle: [ - "await affitor.trackSale({", - " customerExternalId: data.custom_data?.user_id,", - " amount: Number(data.details.totals.total), // cents", - " invoiceId: data.id,", - "});", + "// custom_data is optional, and a $0 total has no revenue: in either case there is", + "// nothing to attribute, and the SDK would throw inside your webhook.", + "const amount = Number(data.details.totals.total); // cents", + "if (data.custom_data?.user_id && Number.isInteger(amount) && amount > 0) {", + " await affitor.trackSale({", + " customerExternalId: data.custom_data.user_id,", + " amount,", + " invoiceId: data.id,", + " });", + "}", ].join("\n"), stripe: [ "// Skip $0 / setup-mode sessions (free trials, $0 invoices) — the SDK rejects", "// a non-positive amount, and there's no revenue to attribute yet.", "if (session.amount_total && session.amount_total > 0) {", - " await affitor.trackSale({", - " // Reads the SAME key the metadata step writes (session.metadata.affitor_customer_key);", - " // client_reference_id is only a fallback for brands that set it explicitly.", - " customerExternalId: session.metadata?.affitor_customer_key ?? session.client_reference_id,", - " amount: session.amount_total, // cents", - " invoiceId: session.id,", - " });", + " // Reads the SAME key the metadata step writes (session.metadata.affitor_customer_key);", + " // client_reference_id is only a fallback for brands that set it explicitly.", + " const affitorKey = session.metadata?.affitor_customer_key ?? session.client_reference_id;", + " if (affitorKey) {", + " await affitor.trackSale({", + " customerExternalId: affitorKey,", + " amount: session.amount_total, // cents", + " invoiceId: session.id,", + " });", + " } else {", + " // No Affitor key on this checkout, so there is nothing to attribute. Log it and", + " // carry on: a throw here would fail your webhook and Stripe would retry it.", + " console.warn(`[affitor] ${session.id} has no affitor_customer_key; sale not reported`);", + " }", "}", ].join("\n"), unknown: [ @@ -253,11 +265,18 @@ const STRIPE_RENEWAL: { snippet: string; inject_target: string; note: string } = " if (invoice.billing_reason !== 'subscription_cycle') break;", " // Skip $0 renewals (100%-off coupons, fully credit-covered) — the SDK rejects a non-positive amount.", " if (!invoice.amount_paid || invoice.amount_paid <= 0) break;", + " // Stripe Basil (2025-03-31+) moved subscription_details under invoice.parent;", + " // read the Basil path first, fall back to the legacy top-level for pre-Basil accounts.", + " const affitorKey = invoice.parent?.subscription_details?.metadata?.affitor_customer_key", + " ?? invoice.subscription_details?.metadata?.affitor_customer_key;", + " // A subscription started without an Affitor key has nothing to attribute. Log it and", + " // carry on: a throw here would fail your webhook and Stripe would retry it.", + " if (!affitorKey) {", + " console.warn(`[affitor] ${invoice.id} has no affitor_customer_key; renewal not reported`);", + " break;", + " }", " await affitor.trackSale({", - " // Stripe Basil (2025-03-31+) moved subscription_details under invoice.parent;", - " // read the Basil path first, fall back to the legacy top-level for pre-Basil accounts.", - " customerExternalId: invoice.parent?.subscription_details?.metadata?.affitor_customer_key", - " ?? invoice.subscription_details?.metadata?.affitor_customer_key,", + " customerExternalId: affitorKey,", " amount: invoice.amount_paid, // integer cents", " invoiceId: invoice.id, // idempotency key — 409 = already recorded", " isRecurring: true,", diff --git a/packages/recipes/tests/recipes.test.ts b/packages/recipes/tests/recipes.test.ts index 85ef0fd..61e4e19 100644 --- a/packages/recipes/tests/recipes.test.ts +++ b/packages/recipes/tests/recipes.test.ts @@ -85,8 +85,9 @@ describe("getRecipe — Stripe sale snippet reads the key the metadata writes (B expect(r.metadata.snippet).toContain("affitor_customer_key: user.id"); // The sale step must READ that same key (with client_reference_id only as a fallback). expect(sale).toContain( - "customerExternalId: session.metadata?.affitor_customer_key ?? session.client_reference_id", + "const affitorKey = session.metadata?.affitor_customer_key ?? session.client_reference_id;", ); + expect(sale).toContain("customerExternalId: affitorKey,"); // It must NOT read client_reference_id alone (the old, attribution-losing contract). expect(sale).not.toMatch(/customerExternalId:\s*session\.client_reference_id,/); }); @@ -148,3 +149,113 @@ describe("getRecipe — subscription renewals (#3 invoice.paid)", () => { expect(plan.steps.some((s) => s.startsWith) && plan.steps.some((s) => /Renewals:/.test(s))).toBe(true); }); }); + +/** + * The snippets run inside the brand's own webhook, so they must never throw there: a throw + * fails the webhook and the provider retries it. The SDK's trackSale throws synchronously + * when it has no customer key (affiliate-sdk server.ts trackSale), so the stub below does the + * same, and each snippet is run for real, with and without the key. + */ +describe("snippets never throw inside the brand's webhook (report 2026-10-17 #5)", () => { + const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; + + function sdkStub() { + const calls: Array> = []; + return { + calls, + // The SDK's three synchronous checks (affiliate-sdk src/server.ts trackSale). + trackSale(input: Record) { + if (!input.customerExternalId && !input.clickId) { + throw new Error("Affitor.trackSale: `customerExternalId` or `clickId` is required"); + } + if (!Number.isInteger(input.amount) || (input.amount as number) <= 0) { + throw new Error("Affitor.trackSale: `amount` must be a positive integer (cents)"); + } + if (!input.invoiceId) { + throw new Error("Affitor.trackSale: `invoiceId` is required (idempotency key)"); + } + calls.push(input); + return Promise.resolve({ ok: true, status: 200 }); + }, + }; + } + + function quietConsole() { + const warnings: string[] = []; + return { warnings, console: { ...console, warn: (...a: unknown[]) => warnings.push(a.join(" ")) } }; + } + + /** The sale body without its import line, run with `vars` in scope. */ + async function runSale(provider: "stripe" | "paddle", vars: Record) { + const body = getRecipe("fastify", provider, "s2s").sale!.snippet.replace(/^import .*\n+/, ""); + const affitor = sdkStub(); + const c = quietConsole(); + const names = [...Object.keys(vars), "affitor", "console"]; + await new AsyncFunction(...names, body)(...Object.values(vars), affitor, c.console); + return { calls: affitor.calls, warnings: c.warnings }; + } + + async function runRenewal(invoice: Record) { + const affitor = sdkStub(); + const c = quietConsole(); + const body = `switch (event.type) {\n${getRecipe("fastify", "stripe", "s2s").renewal!.snippet}\n}`; + await new AsyncFunction("event", "affitor", "console", body)( + { type: "invoice.paid", data: { object: invoice } }, + affitor, + c.console, + ); + return { calls: affitor.calls, warnings: c.warnings }; + } + + it("Stripe checkout without an Affitor key: logs, sends nothing, does not throw", async () => { + const r = await runSale("stripe", { session: { id: "cs_1", amount_total: 4900, metadata: {} } }); + expect(r.calls).toEqual([]); + expect(r.warnings.join("\n")).toContain("cs_1 has no affitor_customer_key"); + }); + + it("Stripe checkout with the key (or only client_reference_id) reports the sale", async () => { + const withKey = await runSale("stripe", { + session: { id: "cs_2", amount_total: 4900, metadata: { affitor_customer_key: "u_1" } }, + }); + expect(withKey.calls).toEqual([{ customerExternalId: "u_1", amount: 4900, invoiceId: "cs_2" }]); + const refOnly = await runSale("stripe", { session: { id: "cs_3", amount_total: 100, client_reference_id: "u_2" } }); + expect(refOnly.calls[0]).toMatchObject({ customerExternalId: "u_2", invoiceId: "cs_3" }); + }); + + it("Stripe $0 checkout: nothing sent, nothing logged", async () => { + const r = await runSale("stripe", { session: { id: "cs_4", amount_total: 0 } }); + expect(r.calls).toEqual([]); + expect(r.warnings).toEqual([]); + }); + + it("Stripe renewal without an Affitor key: logs, sends nothing, does not throw", async () => { + const r = await runRenewal({ id: "in_1", billing_reason: "subscription_cycle", amount_paid: 900 }); + expect(r.calls).toEqual([]); + expect(r.warnings.join("\n")).toContain("in_1 has no affitor_customer_key"); + }); + + it("Stripe renewal with the Basil key reports it", async () => { + const r = await runRenewal({ + id: "in_2", + billing_reason: "subscription_cycle", + amount_paid: 900, + parent: { subscription_details: { metadata: { affitor_customer_key: "u_3" }, subscription: "sub_1" } }, + }); + expect(r.calls).toEqual([ + expect.objectContaining({ customerExternalId: "u_3", amount: 900, invoiceId: "in_2", subscriptionId: "sub_1" }), + ]); + }); + + it("Paddle without custom_data.user_id, or with a $0 total: sends nothing, does not throw", async () => { + const r = await runSale("paddle", { data: { id: "txn_1", details: { totals: { total: "1000" } } } }); + expect(r.calls).toEqual([]); + const zero = await runSale("paddle", { + data: { id: "txn_0", custom_data: { user_id: "u_4" }, details: { totals: { total: "0" } } }, + }); + expect(zero.calls).toEqual([]); + const ok = await runSale("paddle", { + data: { id: "txn_2", custom_data: { user_id: "u_4" }, details: { totals: { total: "1000" } } }, + }); + expect(ok.calls).toEqual([{ customerExternalId: "u_4", amount: 1000, invoiceId: "txn_2" }]); + }); +});