From e2cae90ac730660f6b2ae0ca29f51b11824adc7b Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sat, 17 Oct 2026 19:39:28 -0700 Subject: [PATCH 1/7] fix: onboard adds no trackSale when the program's Stripe is connected; sale snippets never throw without a key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Stripe connected, Affitor records each payment from the connected account, so the injected trackSale recorded a subscription's first payment twice (cs_ and in_ ids). onboard now reads stripe_connected from GET /v1/cli/status: connected → webhook unchanged, Connect recipe printed, an existing trackSale call is pointed out; unknown → ask, or with --yes/--json change nothing. The Stripe sale, Stripe renewal and Paddle snippets skip the call (Stripe ones log) when there is no customer key, instead of letting the SDK throw inside the brand's webhook. Tests run each snippet for real against an SDK-like stub. Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/cli/README.md | 2 +- packages/cli/src/commands/onboard.ts | 85 +++++++++- .../cli/tests/inject-stripe-tracksale.test.ts | 13 +- .../tests/onboard-stripe-connected.test.ts | 158 ++++++++++++++++++ packages/recipes/src/index.ts | 50 ++++-- packages/recipes/tests/recipes.test.ts | 102 ++++++++++- 6 files changed, 385 insertions(+), 25 deletions(-) create mode 100644 packages/cli/tests/onboard-stripe-connected.test.ts diff --git a/packages/cli/README.md b/packages/cli/README.md index dc5e382..3d37722 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -43,7 +43,7 @@ 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. **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). If the program's Stripe is connected in Affitor, nothing is added: Affitor already records each payment from Stripe, and a second call would count it twice. When the CLI cannot tell, it asks; with `--yes` or `--json` it leaves the webhook alone. 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`. diff --git a/packages/cli/src/commands/onboard.ts b/packages/cli/src/commands/onboard.ts index c07b95f..dd488c8 100644 --- a/packages/cli/src/commands/onboard.ts +++ b/packages/cli/src/commands/onboard.ts @@ -114,6 +114,7 @@ export async function runOnboard(opts: OnboardOpts, flags: CLIFlags) { interactive, autoConfirm, json: flags.json, + stripeConnected: provider === "stripe" ? await readStripeConnected(api) : undefined, }); steps.push(saleStep); @@ -166,6 +167,22 @@ interface WireSaleArgs { interactive: boolean; autoConfirm: boolean; json: boolean; + /** The program's Stripe connection in Affitor; undefined when it could not be read. */ + stripeConnected?: boolean; +} + +/** + * Is this program's Stripe connected in Affitor? `GET /v1/cli/status` answers it per program + * (`stripe_connected`, the same check as the dashboard's Payments card). undefined when the + * call fails or the field is missing, so the caller asks instead of guessing. + */ +export async function readStripeConnected(api: Pick): Promise { + try { + const status = await api.getStatus(); + return typeof status?.stripe_connected === "boolean" ? status.stripe_connected : undefined; + } catch { + return undefined; + } } /** @@ -177,7 +194,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 +213,20 @@ 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 = args.stripeConnected; + if (connected === undefined && interactive && !autoConfirm && !json) { + connected = await confirmAction( + "Is Stripe connected for this program in Affitor (Program settings › Payments)?", + ); + } + if (connected !== false) { + return skipSaleForConnect({ cwd, framework, recipe, hook, json, unknown: connected === undefined }); + } + if (!hook) { if (!json) { printRecipe(recipe, null, "Stripe sale (no webhook found — add this where you verify webhooks)"); @@ -271,6 +302,58 @@ async function wireServerSale(args: WireSaleArgs): Promise { return { step: "server_sale", status: "ok", detail: hook.file }; } +/** + * 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 = readFileSync(join(cwd, hook.file), "utf8").includes("trackSale"); + } 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( + `${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, "Add the sale call only if Stripe is not connected in Affitor"); + } 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 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..e5fa65e --- /dev/null +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -0,0 +1,158 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, 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) })); + +const { readStripeConnected, 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(() => { + confirmAction.mockReset(); + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); +}); +afterEach(() => { + vi.restoreAllMocks(); + 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, { stripeConnected: 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, { stripeConnected: true }); + expect(step.status).toBe("skipped"); + expect(step.detail).toContain("already calls trackSale"); + expect(webhookOf(dir)).toBe(wired); + }); +}); + +describe("wireServerSale — Stripe not connected", () => { + it("adds the sale call as before (--yes)", async () => { + const dir = project(); + const step = await wire(dir, { stripeConnected: false }); + expect(step).toMatchObject({ status: "ok", detail: HOOK_FILE }); + expect(webhookOf(dir)).toContain("await affitor.trackSale({"); + }); +}); + +describe("wireServerSale — connection unknown", () => { + it("with --yes (nobody to ask): webhook unchanged, reported as manual", async () => { + const dir = project(); + const step = await wire(dir, { stripeConnected: 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, { stripeConnected: undefined, json: true, autoConfirm: false, interactive: true }); + expect(step.status).toBe("manual"); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it("interactive, answer yes (connected): no trackSale added", async () => { + const dir = project(); + confirmAction.mockResolvedValueOnce(true); + const step = await wire(dir, { stripeConnected: undefined, interactive: true, autoConfirm: false }); + expect(confirmAction).toHaveBeenCalledTimes(1); + expect(confirmAction.mock.calls[0][0]).toContain("Is Stripe connected"); + expect(step.status).toBe("skipped"); + 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, { stripeConnected: undefined, interactive: true, autoConfirm: false }); + expect(confirmAction).toHaveBeenCalledTimes(2); + expect(step.status).toBe("ok"); + expect(webhookOf(dir)).toContain("await affitor.trackSale({"); + }); +}); + +describe("readStripeConnected", () => { + it("reads stripe_connected from GET /v1/cli/status", async () => { + expect(await readStripeConnected({ getStatus: async () => ({ stripe_connected: true }) as never })).toBe(true); + expect(await readStripeConnected({ getStatus: async () => ({ stripe_connected: false }) as never })).toBe(false); + }); + + it("is undefined when the call fails or the field is missing (the caller asks)", async () => { + expect( + await readStripeConnected({ + getStatus: async () => { + throw new Error("network"); + }, + }), + ).toBeUndefined(); + expect(await readStripeConnected({ getStatus: async () => ({}) as never })).toBeUndefined(); + }); +}); diff --git a/packages/recipes/src/index.ts b/packages/recipes/src/index.ts index 00e15c4..270301f 100644 --- a/packages/recipes/src/index.ts +++ b/packages/recipes/src/index.ts @@ -176,23 +176,34 @@ 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: without your user id there is nothing to attribute,", + "// and the SDK would throw inside your webhook.", + "if (data.custom_data?.user_id) {", + " await affitor.trackSale({", + " customerExternalId: data.custom_data.user_id,", + " amount: Number(data.details.totals.total), // cents", + " 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 +264,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..5d0908a 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,102 @@ 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, + trackSale(input: Record) { + if (!input.customerExternalId && !input.clickId) { + throw new Error("Affitor.trackSale: `customerExternalId` or `clickId` is required"); + } + 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: sends nothing, does not throw", async () => { + const r = await runSale("paddle", { data: { id: "txn_1", details: { totals: { total: "1000" } } } }); + expect(r.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" }]); + }); +}); From f66ec314f8d1318b70c02369988d52ebdce06779 Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sat, 17 Oct 2026 19:52:52 -0700 Subject: [PATCH 2/7] fix: onboard trusts only stripe_account_bound; the wizard gives no trackSale advice when Stripe records sales Codex r1 on #41: stripe_connected is false while a bound account is pending_verification, yet Connect still credits its sales, and before CMS v3.16.91 it was true for any Server API program. onboard now reads stripe_account_bound (affiliate-cms#539) and treats its absence as unknown; it reads the binding before the wizard, which then prints the lead step only; a different AFFITOR_API_KEY already in the env file makes the answer unknown; comments mentioning trackSale are not reported as a double count; the Paddle snippet also skips a $0 total. Tests go through runOnboard; the snippet stub checks amount and invoiceId like the SDK. Co-Authored-By: Claude Opus 5.5 (1M context) --- packages/cli/src/commands/onboard.ts | 68 +++++++-- packages/cli/src/lib/wizard.ts | 13 +- packages/cli/src/types.ts | 2 + .../tests/onboard-stripe-connected.test.ts | 140 ++++++++++++++++-- packages/recipes/src/index.ts | 9 +- packages/recipes/tests/recipes.test.ts | 13 +- 6 files changed, 212 insertions(+), 33 deletions(-) diff --git a/packages/cli/src/commands/onboard.ts b/packages/cli/src/commands/onboard.ts index dd488c8..2c415ee 100644 --- a/packages/cli/src/commands/onboard.ts +++ b/packages/cli/src/commands/onboard.ts @@ -96,11 +96,15 @@ 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: stripeAccountBound === true }); steps.push({ step: "browser_tracking", status: "ok", detail: "via install wizard" }); } else { steps.push({ step: "browser_tracking", status: "skipped", detail: "json mode" }); @@ -114,7 +118,7 @@ export async function runOnboard(opts: OnboardOpts, flags: CLIFlags) { interactive, autoConfirm, json: flags.json, - stripeConnected: provider === "stripe" ? await readStripeConnected(api) : undefined, + stripeAccountBound, }); steps.push(saleStep); @@ -167,24 +171,57 @@ interface WireSaleArgs { interactive: boolean; autoConfirm: boolean; json: boolean; - /** The program's Stripe connection in Affitor; undefined when it could not be read. */ - stripeConnected?: boolean; + /** A Stripe account is bound to the program in Affitor; undefined when it could not be read. */ + stripeAccountBound?: boolean; } /** - * Is this program's Stripe connected in Affitor? `GET /v1/cli/status` answers it per program - * (`stripe_connected`, the same check as the dashboard's Payments card). undefined when the - * call fails or the field is missing, so the caller asks instead of guessing. + * 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 readStripeConnected(api: Pick): Promise { +export async function readStripeAccountBound(api: Pick): Promise { try { const status = await api.getStatus(); - return typeof status?.stripe_connected === "boolean" ? status.stripe_connected : undefined; + return typeof status?.stripe_account_bound === "boolean" ? status.stripe_account_bound : undefined; } catch { return undefined; } } +/** The env file onboard writes the key to (.env.local for Next, else .env) and the key already there. */ +export function envApiKey(cwd: string): { envName: string; value?: string } { + const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; + const envPath = join(cwd, envName); + if (!existsSync(envPath)) return { envName }; + const m = readFileSync(envPath, "utf8").match(/^AFFITOR_API_KEY=(.*)$/m); + return { envName, value: m ? m[1].trim() : 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 = envApiKey(cwd); + if (env.value && env.value !== apiKey) { + if (!json) { + logger.warn(`${env.envName} holds a different AFFITOR_API_KEY, so this key's Stripe status may not be the one your app runs with.`); + } + return undefined; + } + return readStripeAccountBound(api); +} + /** * The safety-critical part: locate the Stripe webhook, run the PURE * `injectStripeTrackSale` transform, and: @@ -217,7 +254,7 @@ export async function wireServerSale(args: WireSaleArgs): Promise { // 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 = args.stripeConnected; + let connected = args.stripeAccountBound; if (connected === undefined && interactive && !autoConfirm && !json) { connected = await confirmAction( "Is Stripe connected for this program in Affitor (Program settings › Payments)?", @@ -302,6 +339,11 @@ export async function wireServerSale(args: WireSaleArgs): Promise { return { step: "server_sale", status: "ok", detail: hook.file }; } +/** A trackSale call on a line that is not a comment. */ +export function callsTrackSale(source: string): boolean { + return source.split("\n").some((line) => /\btrackSale\s*\(/.test(line) && !/^\s*(\/\/|\/\*|\*)/.test(line)); +} + /** * 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, @@ -320,7 +362,7 @@ function skipSaleForConnect(args: { let tracksSale = false; if (hook) { try { - tracksSale = readFileSync(join(cwd, hook.file), "utf8").includes("trackSale"); + tracksSale = callsTrackSale(readFileSync(join(cwd, hook.file), "utf8")); } catch { /* unreadable: nothing to point out */ } @@ -332,7 +374,9 @@ function skipSaleForConnect(args: { } if (tracksSale) { logger.warn( - `${hook!.file} calls trackSale. With Stripe connected, Affitor already records each payment, so remove that call or every sale counts twice.`, + unknown + ? `${hook!.file} calls trackSale. If Stripe is connected in Affitor, remove that call: Affitor already records each payment, so every sale would count twice.` + : `${hook!.file} calls trackSale. With Stripe connected, Affitor already records each payment, so remove that call or every sale counts twice.`, ); } if (unknown) { diff --git a/packages/cli/src/lib/wizard.ts b/packages/cli/src/lib/wizard.ts index 880d602..c7e9165 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; + /** Stripe is bound to the program in Affitor: sales and refunds come from Stripe, so no trackSale advice. */ + stripeRecordsSales?: boolean; } 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: true }); + return; + } if (provider === "stripe") { const hook = detectStripeWebhook(opts.cwd, framework); if (hook) { @@ -160,9 +166,14 @@ async function setupServerTracking( printServerSnippets(serverTrackingSnippets(provider)); } -function printServerSnippets(s: TrackingSnippets): void { +function printServerSnippets(s: TrackingSnippets, opts: { salesFromStripe?: boolean } = {}): 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) { + lines.push("", ` ${format.dim("2) Sales and refunds: recorded from your connected Stripe. Do not add trackSale; it would count each payment twice.")}`, ""); + 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..092c6cb 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; + /** A Stripe account is bound to the program, so Affitor records its payments through Connect (affiliate-cms#539). */ + stripe_account_bound?: boolean; recent_events: { clicks_24h: number; leads_24h: number; diff --git a/packages/cli/tests/onboard-stripe-connected.test.ts b/packages/cli/tests/onboard-stripe-connected.test.ts index e5fa65e..7dcccd8 100644 --- a/packages/cli/tests/onboard-stripe-connected.test.ts +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -6,7 +6,32 @@ import { dirname, join } from "node:path"; const confirmAction = vi.fn<(message: string) => Promise>(); vi.mock("../src/lib/prompts.js", () => ({ confirmAction: (m: string) => confirmAction(m) })); -const { readStripeConnected, wireServerSale } = await import("../src/commands/onboard"); +// 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, @@ -63,19 +88,22 @@ function wire(cwd: string, over: Partial[0]> = beforeEach(() => { confirmAction.mockReset(); + wizardCalls.length = 0; + apiState.status = {}; vi.spyOn(console, "log").mockImplementation(() => {}); vi.spyOn(console, "warn").mockImplementation(() => {}); vi.spyOn(console, "error").mockImplementation(() => {}); }); afterEach(() => { 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, { stripeConnected: true }); + 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); @@ -85,7 +113,7 @@ describe("wireServerSale — Stripe connected in Affitor", () => { 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, { stripeConnected: true }); + const step = await wire(dir, { stripeAccountBound: true }); expect(step.status).toBe("skipped"); expect(step.detail).toContain("already calls trackSale"); expect(webhookOf(dir)).toBe(wired); @@ -95,7 +123,7 @@ describe("wireServerSale — Stripe connected in Affitor", () => { describe("wireServerSale — Stripe not connected", () => { it("adds the sale call as before (--yes)", async () => { const dir = project(); - const step = await wire(dir, { stripeConnected: false }); + const step = await wire(dir, { stripeAccountBound: false }); expect(step).toMatchObject({ status: "ok", detail: HOOK_FILE }); expect(webhookOf(dir)).toContain("await affitor.trackSale({"); }); @@ -104,7 +132,7 @@ describe("wireServerSale — Stripe not connected", () => { describe("wireServerSale — connection unknown", () => { it("with --yes (nobody to ask): webhook unchanged, reported as manual", async () => { const dir = project(); - const step = await wire(dir, { stripeConnected: undefined }); + const step = await wire(dir, { stripeAccountBound: undefined }); expect(step.status).toBe("manual"); expect(step.detail).toContain("unknown"); expect(webhookOf(dir)).toBe(WEBHOOK); @@ -113,7 +141,7 @@ describe("wireServerSale — connection unknown", () => { it("in --json mode: webhook unchanged, nobody asked", async () => { const dir = project(); - const step = await wire(dir, { stripeConnected: undefined, json: true, autoConfirm: false, interactive: true }); + 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(); @@ -122,7 +150,7 @@ describe("wireServerSale — connection unknown", () => { it("interactive, answer yes (connected): no trackSale added", async () => { const dir = project(); confirmAction.mockResolvedValueOnce(true); - const step = await wire(dir, { stripeConnected: undefined, interactive: true, autoConfirm: false }); + const step = await wire(dir, { stripeAccountBound: undefined, interactive: true, autoConfirm: false }); expect(confirmAction).toHaveBeenCalledTimes(1); expect(confirmAction.mock.calls[0][0]).toContain("Is Stripe connected"); expect(step.status).toBe("skipped"); @@ -132,27 +160,109 @@ describe("wireServerSale — connection unknown", () => { 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, { stripeConnected: undefined, interactive: true, autoConfirm: false }); + 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("readStripeConnected", () => { - it("reads stripe_connected from GET /v1/cli/status", async () => { - expect(await readStripeConnected({ getStatus: async () => ({ stripe_connected: true }) as never })).toBe(true); - expect(await readStripeConnected({ getStatus: async () => ({ stripe_connected: false }) as never })).toBe(false); +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 }))).toBe(false); }); - it("is undefined when the call fails or the field is missing (the caller asks)", async () => { + 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 readStripeConnected({ + await readStripeAccountBound({ getStatus: async () => { throw new Error("network"); }, }), ).toBeUndefined(); - expect(await readStripeConnected({ getStatus: async () => ({}) as never })).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); + expect(callsTrackSale(" * see trackSale(input)")).toBe(false); + }); + + 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): 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 = {}) { + const cwd = process.cwd(); + process.chdir(dir); + try { + await runOnboard({ apiKey: "key_a", yes: true, ...opts }, 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("not bound: the sale call is added (--yes)", async () => { + apiState.status = { stripe_account_bound: false }; + const dir = app(); + await onboardIn(dir); + expect(webhookOf(dir)).toContain("await affitor.trackSale({"); + expect(wizardCalls[0]).toMatchObject({ stripeRecordsSales: false }); + }); + + 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: false }; + const dir = app("AFFITOR_API_KEY=key_a\n"); + await onboardIn(dir); + expect(webhookOf(dir)).toContain("await affitor.trackSale({"); }); }); diff --git a/packages/recipes/src/index.ts b/packages/recipes/src/index.ts index 270301f..22947ef 100644 --- a/packages/recipes/src/index.ts +++ b/packages/recipes/src/index.ts @@ -176,12 +176,13 @@ const SALE_SNIPPET_BODY: Record = { "});", ].join("\n"), paddle: [ - "// custom_data is optional: without your user id there is nothing to attribute,", - "// and the SDK would throw inside your webhook.", - "if (data.custom_data?.user_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: Number(data.details.totals.total), // cents", + " amount,", " invoiceId: data.id,", " });", "}", diff --git a/packages/recipes/tests/recipes.test.ts b/packages/recipes/tests/recipes.test.ts index 5d0908a..61e4e19 100644 --- a/packages/recipes/tests/recipes.test.ts +++ b/packages/recipes/tests/recipes.test.ts @@ -163,10 +163,17 @@ describe("snippets never throw inside the brand's webhook (report 2026-10-17 #5) 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 }); }, @@ -239,9 +246,13 @@ describe("snippets never throw inside the brand's webhook (report 2026-10-17 #5) ]); }); - it("Paddle without custom_data.user_id: sends nothing, does not throw", async () => { + 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" } } }, }); From cf1624d7a2ec30972c1b9e8129ac1418bcf77a92 Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sat, 17 Oct 2026 21:09:18 -0700 Subject: [PATCH 3/7] fix: treat absent Stripe bindings as unknown during onboarding --- packages/cli/README.md | 2 +- packages/cli/src/commands/onboard.ts | 48 +++++++----- packages/cli/src/lib/wizard.ts | 13 ++-- packages/cli/src/types.ts | 2 +- .../tests/onboard-stripe-connected.test.ts | 74 ++++++++++++++++--- packages/cli/tests/wizard-stripe-mode.test.ts | 47 ++++++++++++ 6 files changed, 147 insertions(+), 39 deletions(-) create mode 100644 packages/cli/tests/wizard-stripe-mode.test.ts diff --git a/packages/cli/README.md b/packages/cli/README.md index 3d37722..148a68f 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -43,7 +43,7 @@ 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). If the program's Stripe is connected in Affitor, nothing is added: Affitor already records each payment from Stripe, and a second call would count it twice. When the CLI cannot tell, it asks; with `--yes` or `--json` it leaves the webhook alone. +3. **Review sale tracking** — if the program has a Stripe account bound in Affitor, the webhook stays unchanged to avoid a second sale path. Otherwise, the CLI asks whether Connect could still report sales, including shared accounts and delayed events after disconnect. Only an interactive answer ruling that out, followed by confirmation of the proposed diff, can add `affitor.trackSale`. `--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`. diff --git a/packages/cli/src/commands/onboard.ts b/packages/cli/src/commands/onboard.ts index 2c415ee..a59f858 100644 --- a/packages/cli/src/commands/onboard.ts +++ b/packages/cli/src/commands/onboard.ts @@ -98,13 +98,19 @@ 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; + const stripeBinding = provider === "stripe" + ? await stripeBindingFor(api, cwd, apiKey, flags.json) + : { bound: undefined, keyMismatch: false }; + const stripeAccountBound = stripeBinding.bound; // ── (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, stripeRecordsSales: stripeAccountBound === true }); + 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" }); @@ -115,7 +121,7 @@ export async function runOnboard(opts: OnboardOpts, flags: CLIFlags) { cwd, framework: stack.framework, provider, - interactive, + interactive: interactive && !stripeBinding.keyMismatch, autoConfirm, json: flags.json, stripeAccountBound, @@ -183,10 +189,12 @@ interface WireSaleArgs { * 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 { +export async function readStripeAccountBound(api: Pick): Promise { try { const status = await api.getStatus(); - return typeof status?.stripe_account_bound === "boolean" ? status.stripe_account_bound : undefined; + // 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; } @@ -197,7 +205,7 @@ export function envApiKey(cwd: string): { envName: string; value?: string } { const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; const envPath = join(cwd, envName); if (!existsSync(envPath)) return { envName }; - const m = readFileSync(envPath, "utf8").match(/^AFFITOR_API_KEY=(.*)$/m); + const m = readFileSync(envPath, "utf8").match(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=(.*)$/m); return { envName, value: m ? m[1].trim() : undefined }; } @@ -211,15 +219,16 @@ async function stripeBindingFor( cwd: string, apiKey: string, json: boolean, -): Promise { +): Promise<{ bound: true | undefined; keyMismatch: boolean }> { const env = envApiKey(cwd); - if (env.value && env.value !== apiKey) { + const processKey = process.env.AFFITOR_API_KEY; + if ((env.value !== undefined && env.value !== apiKey) || (processKey && processKey !== apiKey)) { if (!json) { - logger.warn(`${env.envName} holds a different AFFITOR_API_KEY, so this key's Stripe status may not be the one your app runs with.`); + logger.warn(`The existing AFFITOR_API_KEY in the environment or ${env.envName} may differ from this key. Resolve that conflict before adding sale tracking.`); } - return undefined; + return { bound: undefined, keyMismatch: true }; } - return readStripeAccountBound(api); + return { bound: await readStripeAccountBound(api), keyMismatch: false }; } /** @@ -254,10 +263,10 @@ export async function wireServerSale(args: WireSaleArgs): Promise { // 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 = args.stripeAccountBound; + let connected: boolean | undefined = args.stripeAccountBound === true ? true : undefined; if (connected === undefined && interactive && !autoConfirm && !json) { connected = await confirmAction( - "Is Stripe connected for this program in Affitor (Program settings › Payments)?", + "Could Stripe Connect still report sales for this program (including a shared account or delayed events after disconnect)?", ); } if (connected !== false) { @@ -380,7 +389,7 @@ function skipSaleForConnect(args: { ); } if (unknown) { - printRecipe(recipe, hook, "Add the sale call only if Stripe is not connected in Affitor"); + printRecipe(recipe, hook, "Review manually: add a sale call only after ruling out current, shared-account and delayed Connect events"); } else { printRecipe( getRecipe(toRecipeFramework(framework), "stripe", "stripe_connect"), @@ -454,23 +463,22 @@ function writeApiKeyToEnv( apiKey: string, opts: { autoConfirm: boolean; json: boolean }, ): OnboardStep { - const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; + const { envName, value: existingValue } = envApiKey(cwd); 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 (existingValue !== undefined) { + if (existingValue === 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}`); + logger.step(`To use this key instead, update AFFITOR_API_KEY in ${envName} manually.`); } return { step: "env_key", status: "manual", detail: `${envName}: existing value kept` }; } @@ -485,7 +493,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/wizard.ts b/packages/cli/src/lib/wizard.ts index c7e9165..ab9bd06 100644 --- a/packages/cli/src/lib/wizard.ts +++ b/packages/cli/src/lib/wizard.ts @@ -24,8 +24,8 @@ export interface WizardOptions { programId: string | number; apiUrl: string; autoConfirm: boolean; - /** Stripe is bound to the program in Affitor: sales and refunds come from Stripe, so no trackSale advice. */ - stripeRecordsSales?: boolean; + /** true: bound now; unknown: onboarding cannot rule out Connect. Both suppress sale advice. */ + stripeRecordsSales?: true | "unknown"; } function rel(cwd: string, p: string): string { @@ -148,7 +148,7 @@ async function setupServerTracking( // (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: true }); + printServerSnippets(serverTrackingSnippets(provider), { salesFromStripe: opts.stripeRecordsSales }); return; } if (provider === "stripe") { @@ -166,11 +166,14 @@ async function setupServerTracking( printServerSnippets(serverTrackingSnippets(provider)); } -function printServerSnippets(s: TrackingSnippets, opts: { salesFromStripe?: boolean } = {}): 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) { - lines.push("", ` ${format.dim("2) Sales and refunds: recorded from your connected Stripe. Do not add trackSale; it would count each payment twice.")}`, ""); + 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; } diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.ts index 092c6cb..59fcd15 100644 --- a/packages/cli/src/types.ts +++ b/packages/cli/src/types.ts @@ -67,7 +67,7 @@ export interface ProgramStatus { dns_verified: boolean; stripe_connected: boolean; stripe_charges_enabled?: boolean; - /** A Stripe account is bound to the program, so Affitor records its payments through Connect (affiliate-cms#539). */ + /** Current Stripe binding only. false does not rule out delayed/shared-account Connect events. */ stripe_account_bound?: boolean; recent_events: { clicks_24h: number; diff --git a/packages/cli/tests/onboard-stripe-connected.test.ts b/packages/cli/tests/onboard-stripe-connected.test.ts index 7dcccd8..92a1685 100644 --- a/packages/cli/tests/onboard-stripe-connected.test.ts +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -87,6 +87,7 @@ function wire(cwd: string, over: Partial[0]> = } beforeEach(() => { + vi.stubEnv("AFFITOR_API_KEY", undefined); confirmAction.mockReset(); wizardCalls.length = 0; apiState.status = {}; @@ -95,6 +96,7 @@ beforeEach(() => { vi.spyOn(console, "error").mockImplementation(() => {}); }); afterEach(() => { + vi.unstubAllEnvs(); vi.restoreAllMocks(); process.exitCode = undefined; while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); @@ -121,11 +123,11 @@ describe("wireServerSale — Stripe connected in Affitor", () => { }); describe("wireServerSale — Stripe not connected", () => { - it("adds the sale call as before (--yes)", async () => { + 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).toMatchObject({ status: "ok", detail: HOOK_FILE }); - expect(webhookOf(dir)).toContain("await affitor.trackSale({"); + expect(step.status).toBe("manual"); + expect(webhookOf(dir)).toBe(WEBHOOK); }); }); @@ -152,7 +154,8 @@ describe("wireServerSale — connection unknown", () => { 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("Is Stripe connected"); + expect(confirmAction.mock.calls[0][0]).toContain("Could Stripe Connect still report sales"); + expect(confirmAction.mock.calls[0][0]).toContain("delayed events after disconnect"); expect(step.status).toBe("skipped"); expect(webhookOf(dir)).toBe(WEBHOOK); }); @@ -172,7 +175,7 @@ describe("readStripeAccountBound", () => { 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 }))).toBe(false); + 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 () => { @@ -217,11 +220,11 @@ function app(env?: string): string { return dir; } -async function onboardIn(dir: string, opts: Record = {}) { +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); + await runOnboard({ apiKey: "key_a", yes: true, ...opts }, { ...FLAGS, ...flags }); } finally { process.chdir(cwd); } @@ -236,12 +239,12 @@ describe("runOnboard reads the binding and passes it on", () => { expect(wizardCalls[0]).toMatchObject({ stripeRecordsSales: true }); }); - it("not bound: the sale call is added (--yes)", async () => { + 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)).toContain("await affitor.trackSale({"); - expect(wizardCalls[0]).toMatchObject({ stripeRecordsSales: false }); + 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 () => { @@ -260,9 +263,56 @@ describe("runOnboard reads the binding and passes it on", () => { }); it("the env file holds the same key: the answer is used", async () => { - apiState.status = { stripe_account_bound: false }; + apiState.status = { stripe_account_bound: true }; const dir = app("AFFITOR_API_KEY=key_a\n"); await onboardIn(dir); - expect(webhookOf(dir)).toContain("await affitor.trackSale({"); + 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.mockResolvedValue(false); + await onboardIn(dir, { yes: false }); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + it('a runtime process key conflict cannot be overridden by answering the Connect question', async () => { + vi.stubEnv('AFFITOR_API_KEY', 'key_b'); + apiState.status = { stripe_account_bound: false }; + const dir = app(); + confirmAction.mockResolvedValue(false); + await onboardIn(dir, { yes: false }); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(confirmAction).not.toHaveBeenCalled(); + }); + + 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('); + }); +}); From e0e038c7888160d06fedafb8c9290cff376ce098 Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sat, 17 Oct 2026 21:10:11 -0700 Subject: [PATCH 4/7] test: confirm proposed diffs when checking onboarding key conflicts --- packages/cli/tests/onboard-stripe-connected.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cli/tests/onboard-stripe-connected.test.ts b/packages/cli/tests/onboard-stripe-connected.test.ts index 92a1685..977ee92 100644 --- a/packages/cli/tests/onboard-stripe-connected.test.ts +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -291,7 +291,7 @@ describe("runOnboard reads the binding and passes it on", () => { 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.mockResolvedValue(false); + confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); await onboardIn(dir, { yes: false }); expect(webhookOf(dir)).toBe(WEBHOOK); expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); @@ -302,7 +302,7 @@ describe("runOnboard reads the binding and passes it on", () => { vi.stubEnv('AFFITOR_API_KEY', 'key_b'); apiState.status = { stripe_account_bound: false }; const dir = app(); - confirmAction.mockResolvedValue(false); + confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); await onboardIn(dir, { yes: false }); expect(webhookOf(dir)).toBe(WEBHOOK); expect(confirmAction).not.toHaveBeenCalled(); From 8f7da2efec1243d9d7d2e720db0e7ed447c26084 Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sun, 18 Oct 2026 00:11:08 -0700 Subject: [PATCH 5/7] fix: reject ambiguous onboarding keys and refine tracking advice --- packages/cli/README.md | 2 +- packages/cli/src/commands/onboard.ts | 88 +++++++++++++++++-- .../tests/onboard-stripe-connected.test.ts | 53 ++++++++++- 3 files changed, 133 insertions(+), 10 deletions(-) diff --git a/packages/cli/README.md b/packages/cli/README.md index 148a68f..a102b77 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -46,7 +46,7 @@ It runs the **detect → wire → inject → verify** flow: 3. **Review sale tracking** — if the program has a Stripe account bound in Affitor, the webhook stays unchanged to avoid a second sale path. Otherwise, the CLI asks whether Connect could still report sales, including shared accounts and delayed events after disconnect. Only an interactive answer ruling that out, followed by confirmation of the proposed diff, can add `affitor.trackSale`. `--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`. Multiple assignments are treated as a conflict: resolve them manually before trusting the Connect status or adding sale tracking. | Flag | Description | |---|---| diff --git a/packages/cli/src/commands/onboard.ts b/packages/cli/src/commands/onboard.ts index a59f858..f7f2d1c 100644 --- a/packages/cli/src/commands/onboard.ts +++ b/packages/cli/src/commands/onboard.ts @@ -9,7 +9,7 @@ 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 { runInstallWizard } from "../lib/wizard.js"; @@ -201,12 +201,17 @@ export async function readStripeAccountBound(api: Pick) } /** The env file onboard writes the key to (.env.local for Next, else .env) and the key already there. */ -export function envApiKey(cwd: string): { envName: string; value?: string } { +export function envApiKey(cwd: string): { envName: string; value?: string; ambiguous?: boolean } { const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; const envPath = join(cwd, envName); if (!existsSync(envPath)) return { envName }; - const m = readFileSync(envPath, "utf8").match(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=(.*)$/m); - return { envName, value: m ? m[1].trim() : undefined }; + const assignments = readFileSync(envPath, "utf8").split(/\r?\n/) + .filter(line => /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=/.test(line)); + // Frameworks and dotenv loaders differ on precedence. Never choose one assignment + // on the application's behalf, even when duplicate values happen to match today. + if (assignments.length > 1) return { envName, ambiguous: true }; + const value = assignments[0]?.replace(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*/, "").trim(); + return { envName, value }; } /** @@ -222,7 +227,7 @@ async function stripeBindingFor( ): Promise<{ bound: true | undefined; keyMismatch: boolean }> { const env = envApiKey(cwd); const processKey = process.env.AFFITOR_API_KEY; - if ((env.value !== undefined && env.value !== apiKey) || (processKey && processKey !== apiKey)) { + if (env.ambiguous || (env.value !== undefined && env.value !== apiKey) || (processKey && processKey !== apiKey)) { if (!json) { logger.warn(`The existing AFFITOR_API_KEY in the environment or ${env.envName} may differ from this key. Resolve that conflict before adding sale tracking.`); } @@ -273,6 +278,13 @@ export async function wireServerSale(args: WireSaleArgs): Promise { 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)"); @@ -348,9 +360,65 @@ export async function wireServerSale(args: WireSaleArgs): Promise { return { step: "server_sale", status: "ok", detail: hook.file }; } -/** A trackSale call on a line that is not a comment. */ +/** Find call tokens outside comments/literals; template interpolation is executable code. */ export function callsTrackSale(source: string): boolean { - return source.split("\n").some((line) => /\btrackSale\s*\(/.test(line) && !/^\s*(\/\/|\/\*|\*)/.test(line)); + 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 (c === "(" && previous === "trackSale") found = true; + if (c === "{") depth++; + if (c === "}") { if (interpolation && depth === 0) { i++; return; } depth--; } + previous = c; i++; + } + } + code(); + return found; } /** @@ -463,13 +531,17 @@ function writeApiKeyToEnv( apiKey: string, opts: { autoConfirm: boolean; json: boolean }, ): OnboardStep { - const { envName, value: existingValue } = envApiKey(cwd); + const { envName, value: existingValue, ambiguous } = envApiKey(cwd); const envPath = join(cwd, envName); const line = `AFFITOR_API_KEY=${apiKey}`; let content = ""; if (existsSync(envPath)) { content = readFileSync(envPath, "utf8"); + if (ambiguous) { + if (!opts.json) logger.warn(`${envName} has multiple AFFITOR_API_KEY assignments — resolve them manually. Nothing was changed.`); + return { step: "env_key", status: "manual", detail: `${envName}: duplicate assignments kept` }; + } if (existingValue !== undefined) { if (existingValue === apiKey) { if (!opts.json) logger.step(`${envName} already has AFFITOR_API_KEY — skipped`); diff --git a/packages/cli/tests/onboard-stripe-connected.test.ts b/packages/cli/tests/onboard-stripe-connected.test.ts index 977ee92..c59f25b 100644 --- a/packages/cli/tests/onboard-stripe-connected.test.ts +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -199,9 +199,29 @@ describe("callsTrackSale", () => { expect(callsTrackSale("await affitor.trackSale({ invoiceId })")).toBe(true); expect(callsTrackSale("// trackSale is documented elsewhere")).toBe(false); expect(callsTrackSale(" // await affitor.trackSale({})")).toBe(false); - expect(callsTrackSale(" * see trackSale(input)")).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 = `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); @@ -298,6 +318,37 @@ describe("runOnboard reads the binding and passes it on", () => { expect(confirmAction).not.toHaveBeenCalled(); }); + 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(false); + await onboardIn(dir, { yes: false }, flags); + expect(webhookOf(dir)).toBe(WEBHOOK); + expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); + 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' })); + } 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('a runtime process key conflict cannot be overridden by answering the Connect question', async () => { vi.stubEnv('AFFITOR_API_KEY', 'key_b'); apiState.status = { stripe_account_bound: false }; From f410659fa418c001963325776706c46fa6e451d2 Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sun, 18 Oct 2026 00:21:41 -0700 Subject: [PATCH 6/7] fix: refuse conflicting onboarding keys across runtime env layers --- packages/cli/README.md | 2 +- packages/cli/src/commands/onboard.ts | 50 ++++++++------ .../tests/onboard-stripe-connected.test.ts | 68 ++++++++++++++++++- 3 files changed, 97 insertions(+), 23 deletions(-) diff --git a/packages/cli/README.md b/packages/cli/README.md index a102b77..c774488 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -46,7 +46,7 @@ It runs the **detect → wire → inject → verify** flow: 3. **Review sale tracking** — if the program has a Stripe account bound in Affitor, the webhook stays unchanged to avoid a second sale path. Otherwise, the CLI asks whether Connect could still report sales, including shared accounts and delayed events after disconnect. Only an interactive answer ruling that out, followed by confirmation of the proposed diff, can add `affitor.trackSale`. `--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`. Multiple assignments are treated as a conflict: resolve them manually before trusting the Connect status or adding sale tracking. +It is **idempotent** — re-running skips work already done (existing env key, sale call already present) and never overwrites a different `AFFITOR_API_KEY`. Duplicate assignments or conflicts across `.env`, `.env.local`, and `.env.{production,development,test}[.local]` force manual review and leave all env files unchanged. This is deliberately conservative: even a conflict in another runtime mode must be resolved before trusting the Connect status or adding sale tracking. The CLI does not guess which mode you deploy. | Flag | Description | |---|---| diff --git a/packages/cli/src/commands/onboard.ts b/packages/cli/src/commands/onboard.ts index f7f2d1c..350f7de 100644 --- a/packages/cli/src/commands/onboard.ts +++ b/packages/cli/src/commands/onboard.ts @@ -200,18 +200,28 @@ export async function readStripeAccountBound(api: Pick) } } -/** The env file onboard writes the key to (.env.local for Next, else .env) and the key already there. */ -export function envApiKey(cwd: string): { envName: string; value?: string; ambiguous?: boolean } { +/** + * Inspect every standard runtime mode instead of guessing the deployment's NODE_ENV. + * Next's mode-local layer precedes .env.local; test skips .env.local entirely. + * Requiring all declared keys to agree is deliberately stricter than any one loader. + */ +export function envApiKey(cwd: string, expectedKey: string): { envName: string; value?: string; ambiguous?: boolean; conflict: boolean } { const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; - const envPath = join(cwd, envName); - if (!existsSync(envPath)) return { envName }; - const assignments = readFileSync(envPath, "utf8").split(/\r?\n/) - .filter(line => /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=/.test(line)); - // Frameworks and dotenv loaders differ on precedence. Never choose one assignment - // on the application's behalf, even when duplicate values happen to match today. - if (assignments.length > 1) return { envName, ambiguous: true }; - const value = assignments[0]?.replace(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*/, "").trim(); - return { envName, value }; + const names = [".env", ".env.local", ...["production", "development", "test"].flatMap(mode => [`.env.${mode}`, `.env.${mode}.local`])]; + const layers = names.map(name => { + const path = join(cwd, name); + const assignments = existsSync(path) ? readFileSync(path, "utf8").split(/\r?\n/) + .filter(line => /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=/.test(line)) : []; + let value = assignments[0]?.replace(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*/, "").trim(); + if (value && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) value = value.slice(1, -1); + return { name, value, ambiguous: assignments.length > 1 }; + }); + const target = layers.find(layer => layer.name === envName)!; + return { + envName, value: target.value, ambiguous: target.ambiguous, + conflict: (process.env.AFFITOR_API_KEY !== undefined && process.env.AFFITOR_API_KEY !== expectedKey) + || layers.some(layer => layer.ambiguous || (layer.value !== undefined && layer.value !== expectedKey)), + }; } /** @@ -225,11 +235,10 @@ async function stripeBindingFor( apiKey: string, json: boolean, ): Promise<{ bound: true | undefined; keyMismatch: boolean }> { - const env = envApiKey(cwd); - const processKey = process.env.AFFITOR_API_KEY; - if (env.ambiguous || (env.value !== undefined && env.value !== apiKey) || (processKey && processKey !== apiKey)) { + const env = envApiKey(cwd, apiKey); + if (env.conflict) { if (!json) { - logger.warn(`The existing AFFITOR_API_KEY in the environment or ${env.envName} may differ from this key. Resolve that conflict before adding sale tracking.`); + logger.warn(`AFFITOR_API_KEY assignments in process.env or the project env layers conflict with this key. Resolve them for every runtime mode before adding sale tracking.`); } return { bound: undefined, keyMismatch: true }; } @@ -411,6 +420,7 @@ export function callsTrackSale(source: string): boolean { 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--; } @@ -531,17 +541,17 @@ function writeApiKeyToEnv( apiKey: string, opts: { autoConfirm: boolean; json: boolean }, ): OnboardStep { - const { envName, value: existingValue, ambiguous } = envApiKey(cwd); + const { envName, value: existingValue, conflict } = envApiKey(cwd, apiKey); const envPath = join(cwd, envName); const line = `AFFITOR_API_KEY=${apiKey}`; + if (conflict) { + if (!opts.json) logger.warn("Project env layers have conflicting or duplicate AFFITOR_API_KEY assignments — resolve them manually. Nothing was changed."); + return { step: "env_key", status: "manual", detail: "env layer conflict: existing assignments kept" }; + } let content = ""; if (existsSync(envPath)) { content = readFileSync(envPath, "utf8"); - if (ambiguous) { - if (!opts.json) logger.warn(`${envName} has multiple AFFITOR_API_KEY assignments — resolve them manually. Nothing was changed.`); - return { step: "env_key", status: "manual", detail: `${envName}: duplicate assignments kept` }; - } if (existingValue !== undefined) { if (existingValue === apiKey) { if (!opts.json) logger.step(`${envName} already has AFFITOR_API_KEY — skipped`); diff --git a/packages/cli/tests/onboard-stripe-connected.test.ts b/packages/cli/tests/onboard-stripe-connected.test.ts index c59f25b..9579a16 100644 --- a/packages/cli/tests/onboard-stripe-connected.test.ts +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -208,6 +208,7 @@ describe("callsTrackSale", () => { "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); @@ -259,6 +260,25 @@ describe("runOnboard reads the binding and passes it on", () => { 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(); @@ -349,8 +369,52 @@ describe("runOnboard reads the binding and passes it on", () => { expect(output).toContain('same id you passed to trackSale'); }); - it('a runtime process key conflict cannot be overridden by answering the Connect question', async () => { - vi.stubEnv('AFFITOR_API_KEY', 'key_b'); + 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(false).mockResolvedValueOnce(true); + await onboardIn(dir, { yes: false }); + expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); + expect(confirmAction).not.toHaveBeenCalled(); + 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.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(false).mockResolvedValueOnce(true); From e8a72c3889daa6d2c87c3ab82ba104da9e35fba9 Mon Sep 17 00:00:00 2001 From: sonpiaz Date: Sun, 18 Oct 2026 00:40:36 -0700 Subject: [PATCH 7/7] fix: ask before changing sale tracking when runtime credentials are uncertain --- package-lock.json | 15 +- packages/cli/README.md | 4 +- packages/cli/package.json | 5 +- packages/cli/src/commands/onboard.ts | 85 ++++-------- packages/cli/src/lib/project-env.ts | 74 ++++++++++ .../tests/onboard-stripe-connected.test.ts | 128 ++++++++++++++++-- 6 files changed, 234 insertions(+), 77 deletions(-) create mode 100644 packages/cli/src/lib/project-env.ts 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 3859d9f..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. **Review sale tracking** — if the program has a Stripe account bound in Affitor, the webhook stays unchanged to avoid a second sale path. Otherwise, the CLI asks whether Connect could still report sales, including shared accounts and delayed events after disconnect. Only an interactive answer ruling that out, followed by confirmation of the proposed diff, can add `affitor.trackSale`. `--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. +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`. Duplicate assignments or conflicts across `.env`, `.env.local`, and `.env.{production,development,test}[.local]` force manual review and leave all env files unchanged. This is deliberately conservative: even a conflict in another runtime mode must be resolved before trusting the Connect status or adding sale tracking. The CLI does not guess which mode you deploy. +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 350f7de..3a6741e 100644 --- a/packages/cli/src/commands/onboard.ts +++ b/packages/cli/src/commands/onboard.ts @@ -12,6 +12,7 @@ import { detectStack, type Framework } from "../lib/stack-detect.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"; @@ -98,10 +99,9 @@ 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 stripeBinding = provider === "stripe" + const stripeAccountBound = provider === "stripe" ? await stripeBindingFor(api, cwd, apiKey, flags.json) - : { bound: undefined, keyMismatch: false }; - const stripeAccountBound = stripeBinding.bound; + : undefined; // ── (c) Browser tracking — reuse init's wizard (install @affitor/sdk + // inject via diff-preview+confirm + scaffold lib/affitor.ts). @@ -121,7 +121,7 @@ export async function runOnboard(opts: OnboardOpts, flags: CLIFlags) { cwd, framework: stack.framework, provider, - interactive: interactive && !stripeBinding.keyMismatch, + interactive, autoConfirm, json: flags.json, stripeAccountBound, @@ -200,30 +200,6 @@ export async function readStripeAccountBound(api: Pick) } } -/** - * Inspect every standard runtime mode instead of guessing the deployment's NODE_ENV. - * Next's mode-local layer precedes .env.local; test skips .env.local entirely. - * Requiring all declared keys to agree is deliberately stricter than any one loader. - */ -export function envApiKey(cwd: string, expectedKey: string): { envName: string; value?: string; ambiguous?: boolean; conflict: boolean } { - const envName = existsSync(join(cwd, ".env.local")) ? ".env.local" : ".env"; - const names = [".env", ".env.local", ...["production", "development", "test"].flatMap(mode => [`.env.${mode}`, `.env.${mode}.local`])]; - const layers = names.map(name => { - const path = join(cwd, name); - const assignments = existsSync(path) ? readFileSync(path, "utf8").split(/\r?\n/) - .filter(line => /^\s*(?:export\s+)?AFFITOR_API_KEY\s*=/.test(line)) : []; - let value = assignments[0]?.replace(/^\s*(?:export\s+)?AFFITOR_API_KEY\s*=\s*/, "").trim(); - if (value && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) value = value.slice(1, -1); - return { name, value, ambiguous: assignments.length > 1 }; - }); - const target = layers.find(layer => layer.name === envName)!; - return { - envName, value: target.value, ambiguous: target.ambiguous, - conflict: (process.env.AFFITOR_API_KEY !== undefined && process.env.AFFITOR_API_KEY !== expectedKey) - || layers.some(layer => layer.ambiguous || (layer.value !== undefined && layer.value !== expectedKey)), - }; -} - /** * 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 @@ -234,15 +210,15 @@ async function stripeBindingFor( cwd: string, apiKey: string, json: boolean, -): Promise<{ bound: true | undefined; keyMismatch: boolean }> { - const env = envApiKey(cwd, apiKey); - if (env.conflict) { +): Promise { + const env = inspectProjectEnvironment(cwd, apiKey); + if (!env.certain) { if (!json) { - logger.warn(`AFFITOR_API_KEY assignments in process.env or the project env layers conflict with this key. Resolve them for every runtime mode before adding sale tracking.`); + logger.warn(`The app runtime key is uncertain (${env.reason}); review all env layers and the program before changing sale tracking.`); } - return { bound: undefined, keyMismatch: true }; + return undefined; } - return { bound: await readStripeAccountBound(api), keyMismatch: false }; + return readStripeAccountBound(api); } /** @@ -279,9 +255,11 @@ export async function wireServerSale(args: WireSaleArgs): Promise { // ask, change nothing. let connected: boolean | undefined = args.stripeAccountBound === true ? true : undefined; if (connected === undefined && interactive && !autoConfirm && !json) { - connected = await confirmAction( - "Could Stripe Connect still report sales for this program (including a shared account or delayed events after disconnect)?", + 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 }); @@ -462,12 +440,12 @@ function skipSaleForConnect(args: { if (tracksSale) { logger.warn( unknown - ? `${hook!.file} calls trackSale. If Stripe is connected in Affitor, remove that call: Affitor already records each payment, so every sale would count twice.` + ? `${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, "Review manually: add a sale call only after ruling out current, shared-account and delayed Connect events"); + 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"), @@ -541,30 +519,19 @@ function writeApiKeyToEnv( apiKey: string, opts: { autoConfirm: boolean; json: boolean }, ): OnboardStep { - const { envName, value: existingValue, conflict } = envApiKey(cwd, apiKey); + const env = inspectProjectEnvironment(cwd, apiKey); + const { envName } = env; const envPath = join(cwd, envName); const line = `AFFITOR_API_KEY=${apiKey}`; - - if (conflict) { - if (!opts.json) logger.warn("Project env layers have conflicting or duplicate AFFITOR_API_KEY assignments — resolve them manually. Nothing was changed."); - return { step: "env_key", status: "manual", detail: "env layer conflict: existing assignments kept" }; - } - let content = ""; - if (existsSync(envPath)) { - content = readFileSync(envPath, "utf8"); - if (existingValue !== undefined) { - if (existingValue === 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, update AFFITOR_API_KEY in ${envName} manually.`); - } - 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) 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/tests/onboard-stripe-connected.test.ts b/packages/cli/tests/onboard-stripe-connected.test.ts index 9579a16..3517440 100644 --- a/packages/cli/tests/onboard-stripe-connected.test.ts +++ b/packages/cli/tests/onboard-stripe-connected.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, mkdtempSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -149,14 +149,14 @@ describe("wireServerSale — connection unknown", () => { expect(confirmAction).not.toHaveBeenCalled(); }); - it("interactive, answer yes (connected): no trackSale added", async () => { + 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("Could Stripe Connect still report sales"); + 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("skipped"); + expect(step.status).toBe("manual"); expect(webhookOf(dir)).toBe(WEBHOOK); }); @@ -234,7 +234,7 @@ describe("callsTrackSale", () => { 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): string { +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); @@ -331,11 +331,11 @@ describe("runOnboard reads the binding and passes it on", () => { 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(false).mockResolvedValueOnce(true); + confirmAction.mockResolvedValueOnce(true); await onboardIn(dir, { yes: false }); expect(webhookOf(dir)).toBe(WEBHOOK); expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); - expect(confirmAction).not.toHaveBeenCalled(); + expect(confirmAction).toHaveBeenCalledTimes(1); }); it.each([ @@ -344,11 +344,11 @@ describe("runOnboard reads the binding and passes it on", () => { 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(false); + confirmAction.mockResolvedValue(true); await onboardIn(dir, { yes: false }, flags); expect(webhookOf(dir)).toBe(WEBHOOK); expect(readFileSync(join(dir, '.env'), 'utf8')).toBe(env); - expect(confirmAction).not.toHaveBeenCalled(); + 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' })); @@ -392,10 +392,10 @@ describe("runOnboard reads the binding and passes it on", () => { const env = 'AFFITOR_API_KEY=key_b\n'; writeFileSync(join(dir, layer), env); apiState.status = { stripe_account_bound: true }; - confirmAction.mockResolvedValueOnce(false).mockResolvedValueOnce(true); + confirmAction.mockResolvedValueOnce(true); await onboardIn(dir, { yes: false }); expect(wizardCalls[0].stripeRecordsSales).toBe('unknown'); - expect(confirmAction).not.toHaveBeenCalled(); + 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'); @@ -413,14 +413,116 @@ describe("runOnboard reads the binding and passes it on", () => { 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(false).mockResolvedValueOnce(true); + confirmAction.mockResolvedValueOnce(true); await onboardIn(dir, { yes: false }); expect(webhookOf(dir)).toBe(WEBHOOK); - expect(confirmAction).not.toHaveBeenCalled(); + 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) => {