Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: attribute signups retried after a partial callback (#973)

opencomputer-app[bot]5d92de565247
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index b8e8a6f3..9f74492c 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -3832,12 +3832,22 @@ interface ProvisionedIdentity {
name: string;
plan: string;
};
- /** True when this login created the user row: a signup. */
+ /**
+ * True when this login is part of a signup: it created the user row, or the
+ * row is younger than SIGNUP_RETRY_WINDOW_SEC (a signup whose first callback
+ * failed after the insert and was retried). Attribution writes are
+ * idempotent, so a repeat inside the window records nothing new.
+ */
created: boolean;
}
type IdentitySelection = "browser" | "cli";
+// A signup whose callback failed after inserting the user is retried at once
+// (authCallback restarts the login); within this window it still counts as
+// the signup for attribution.
+const SIGNUP_RETRY_WINDOW_SEC = 60 * 60;
+
// A post-login destination is only honored if it is a same-origin PATH: it must
// start with a single "/", carry no host (no "//" protocol-relative form) and no
// backslash tricks. Tampering with the WorkOS `state` can then at most pick a
@@ -3974,12 +3984,12 @@ async function provisionWorkOSIdentity(
[profile.first_name, profile.last_name].filter(Boolean).join(" ") || profile.email;
let userRow = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, email, name FROM users WHERE workos_user_id = ?1`,
+ `SELECT id, email, name, created_at FROM users WHERE workos_user_id = ?1`,
)
.bind(profile.id)
- .first<{ id: string; email: string; name: string | null }>();
+ .first<{ id: string; email: string; name: string | null; created_at: number | null }>();
- let created = false;
+ let created = userRow !== null && nowSec - (userRow.created_at ?? 0) < SIGNUP_RETRY_WINDOW_SEC;
if (!userRow) {
const candidateID = crypto.randomUUID();
await env.OPENCOMPUTER_DB.prepare(
@@ -3999,10 +4009,10 @@ async function provisionWorkOSIdentity(
.run();
// Re-read after the email-conflict path: the existing row retains its id.
userRow = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, email, name FROM users WHERE workos_user_id = ?1`,
+ `SELECT id, email, name, created_at FROM users WHERE workos_user_id = ?1`,
)
.bind(profile.id)
- .first<{ id: string; email: string; name: string | null }>();
+ .first<{ id: string; email: string; name: string | null; created_at: number | null }>();
if (!userRow) throw new Error("workos user upsert did not resolve");
// The email-conflict path keeps an existing account: not a signup.
created = userRow.id === candidateID;
diff --git a/cloudflare-workers/api-edge/src/signup_attribution.test.ts b/cloudflare-workers/api-edge/src/signup_attribution.test.ts
index 531df5ee..282a41fb 100644
--- a/cloudflare-workers/api-edge/src/signup_attribution.test.ts
+++ b/cloudflare-workers/api-edge/src/signup_attribution.test.ts
@@ -46,9 +46,9 @@ class Stmt {
async all<T>(): Promise<{ results: T[] }> {
return { results: this.db.prepare(this.sql).all(...this.args()) as T[] };
}
- async run(): Promise<{ success: true; meta: object }> {
- this.db.prepare(this.sql).run(...this.args());
- return { success: true, meta: {} };
+ async run(): Promise<{ success: true; meta: { changes: number } }> {
+ const out = this.db.prepare(this.sql).run(...this.args()) as { changes?: number | bigint };
+ return { success: true, meta: { changes: Number(out?.changes ?? 0) } };
}
}
@@ -234,6 +234,30 @@ describe("browser signup records attribution", () => {
expect(posthog).toHaveLength(1);
});
+ it("records a signup retried after a partial first callback, once", async () => {
+ // The first callback inserted the user, then failed before the workspace existed.
+ const nowSec = Math.floor(Date.now() / 1000);
+ db.prepare("INSERT INTO users (id, email, workos_user_id, name, created_at) VALUES (?, ?, ?, ?, ?)")
+ .run("u_partial", "[email protected]", "wos_1", "New", nowSec - 30);
+ const res = await callback(`oc_ft=${encodeFirstTouch({ utm_source: "retry" })}`);
+ expect(res.status).toBe(302);
+ expect(db.prepare("SELECT user_id, utm_source FROM signup_attribution").all()).toEqual([
+ { user_id: "u_partial", utm_source: "retry" },
+ ]);
+ await callback(`oc_ft=${encodeFirstTouch({ utm_source: "retry" })}`);
+ expect(posthog.map((e) => e.event)).toEqual(["signed_up"]);
+ });
+
+ it("does not attribute an existing account's login", async () => {
+ const nowSec = Math.floor(Date.now() / 1000);
+ db.prepare("INSERT INTO users (id, email, workos_user_id, name, created_at) VALUES (?, ?, ?, ?, ?)")
+ .run("u_old", "[email protected]", "wos_1", "New", nowSec - 2 * 60 * 60);
+ const res = await callback(`oc_ft=${encodeFirstTouch({ utm_source: "late" })}`);
+ expect(res.status).toBe(302);
+ expect(db.prepare("SELECT * FROM signup_attribution").all()).toEqual([]);
+ expect(posthog).toEqual([]);
+ });
+
it("logs in with a garbage cookie, recording unknown fields", async () => {
const res = await callback("oc_ft=%%%garbage");
expect(res.status).toBe(302);
diff --git a/cloudflare-workers/api-edge/src/signup_attribution.ts b/cloudflare-workers/api-edge/src/signup_attribution.ts
index 584fcbc2..82710df8 100644
--- a/cloudflare-workers/api-edge/src/signup_attribution.ts
+++ b/cloudflare-workers/api-edge/src/signup_attribution.ts
@@ -276,12 +276,15 @@ export function signupPostHogEvent(token: string, row: SignupAttributionRow, org
};
}
-/** Stores the signup's attribution and tells PostHog. Never throws. */
+/**
+ * Stores the signup's attribution and tells PostHog, once per user: a repeat
+ * (a retried signup's later login) writes nothing and sends nothing. Never throws.
+ */
export async function recordSignupAttribution(env: SignupAttributionEnv, input: SignupAttributionInput): Promise<void> {
let row: SignupAttributionRow;
try {
row = signupAttributionRow(input, Math.floor(Date.now() / 1000));
- await env.OPENCOMPUTER_DB.prepare(
+ const result = await env.OPENCOMPUTER_DB.prepare(
`INSERT INTO signup_attribution (
user_id, utm_source, utm_medium, utm_campaign, utm_term, utm_content,
gclid, fbclid, li_fat_id, ref, referrer, landing_path, first_seen_at,
@@ -295,6 +298,7 @@ export async function recordSignupAttribution(env: SignupAttributionEnv, input:
row.channel, row.client, row.auth_method, row.plan_intent, row.created_at,
)
.run();
+ if (!result.meta?.changes) return;
} catch (err) {
console.error(`signup attribution: insert failed for ${input.userId}`, err instanceof Error ? err.message : "");
return;