All files / src/paddle-webhook index.ts

0% Statements 0/220
0% Branches 0/1
0% Functions 0/1
0% Lines 0/220

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";
import { RestError } from "@azure/data-tables";
import { verifyPaddleSignature } from "../services/paddleClient";
import { ensureTable, nowIso } from "../services/tablesService";
import { applySubscriptionState, findByPaddleCustomerId, getByEmail } from "../services/usersStore";
import type { UserEntity } from "../models/user";

/**
 * POST /api/paddle-webhook (contracts/paddle-webhook.md): Paddle is the only
 * caller — anonymous auth level, no withAuth, no function key boundary; the
 * HMAC signature IS the authentication (research.md R4). Registered
 * separately from the other HTTP functions since it takes no Bearer token.
 */

const EVENTS_TABLE = "PaddleEvents";
const EVENTS_PARTITION = "PaddleEvent";

interface PaddleEventPayload {
  event_id: string;
  event_type: string;
  occurred_at: string;
  data: Record<string, unknown>;
}

function isPaddleEventPayload(value: unknown): value is PaddleEventPayload {
  if (typeof value !== "object" || value === null) return false;
  const v = value as Record<string, unknown>;
  return (
    typeof v.event_id === "string" &&
    typeof v.event_type === "string" &&
    typeof v.occurred_at === "string" &&
    typeof v.data === "object" &&
    v.data !== null
  );
}

function jsonResponse(status: number, body: unknown): HttpResponseInit {
  return { status, headers: { "Content-Type": "application/json" }, jsonBody: body };
}

const SUBSCRIPTION_STATUSES = ["active", "past_due", "paused", "canceled"] as const;

function isSubscriptionStatus(
  value: unknown
): value is (typeof SUBSCRIPTION_STATUSES)[number] {
  return (
    typeof value === "string" &&
    (SUBSCRIPTION_STATUSES as readonly string[]).includes(value)
  );
}

/**
 * Maps a handled event to a Users-row patch. `null` means "acknowledged but
 * ignored" (unknown event types) — no user resolution or write is needed.
 */
function buildEventPatch(
  eventType: string,
  data: Record<string, unknown>
): Partial<Omit<UserEntity, "partitionKey" | "rowKey">> | null {
  const customerId = typeof data.customer_id === "string" ? data.customer_id : undefined;

  if (eventType === "transaction.completed") {
    return {
      tier: "premium",
      ...(customerId ? { paddleCustomerId: customerId } : {}),
    };
  }

  if (eventType === "subscription.activated") {
    return {
      tier: "premium",
      subscriptionStatus: "active",
      // Empty string is this table's "cleared" convention (Table Storage
      // Merge has no first-class property deletion) — any scheduled-cancel
      // display state from a prior downgrade attempt no longer applies.
      endsAt: "",
      ...(customerId ? { paddleCustomerId: customerId } : {}),
      ...(typeof data.id === "string" ? { paddleSubscriptionId: data.id } : {}),
      ...(typeof data.next_billed_at === "string" ? { renewsAt: data.next_billed_at } : {}),
    };
  }

  if (eventType === "subscription.updated") {
    // Display state only — never flips tier (contracts/paddle-webhook.md).
    const scheduledChange = data.scheduled_change as
      | { action?: unknown; effective_at?: unknown }
      | null
      | undefined;
    const effectiveAt =
      scheduledChange?.action === "cancel" && typeof scheduledChange.effective_at === "string"
        ? scheduledChange.effective_at
        : "";
    return {
      ...(isSubscriptionStatus(data.status)
        ? { subscriptionStatus: data.status }
        : {}),
      ...(typeof data.next_billed_at === "string"
        ? { renewsAt: data.next_billed_at }
        : {}),
      // Cleared (empty string) when no scheduled cancel is present.
      endsAt: effectiveAt,
    };
  }

  if (eventType === "subscription.canceled") {
    // Paddle sends this when the cancellation takes effect (period end by
    // default) — paid-through is honored by event timing, not our clock.
    return {
      tier: "free",
      subscriptionStatus: "canceled",
      renewsAt: "",
      endsAt: "",
    };
  }

  return null;
}

/** custom_data (from the verified token at checkout) then paddleCustomerId fallback. */
async function resolveUserEmail(data: Record<string, unknown>): Promise<string | null> {
  const customData = data.custom_data as { email?: unknown } | undefined;
  if (typeof customData?.email === "string" && customData.email.length > 0) {
    const user = await getByEmail(customData.email);
    if (user) return user.rowKey;
  }
  const customerId = data.customer_id;
  if (typeof customerId === "string") {
    const user = await findByPaddleCustomerId(customerId);
    if (user) return user.rowKey;
  }
  return null;
}

export async function paddleWebhookHandler(
  request: HttpRequest,
  context: InvocationContext
): Promise<HttpResponseInit> {
  const rawBodyText = await request.text();
  const secret = process.env.PADDLE_WEBHOOK_SECRET ?? "";
  const signatureHeader = request.headers.get("paddle-signature");

  if (
    !secret ||
    !verifyPaddleSignature(Buffer.from(rawBodyText, "utf-8"), signatureHeader, secret)
  ) {
    context.warn("paddle-webhook: signature verification failed");
    return jsonResponse(400, {
      error: { code: "INVALID_SIGNATURE", message: "Invalid or missing signature." },
    });
  }

  let payload: unknown;
  try {
    payload = JSON.parse(rawBodyText);
  } catch {
    return jsonResponse(400, {
      error: { code: "INVALID_REQUEST", message: "Body is not valid JSON." },
    });
  }
  if (!isPaddleEventPayload(payload)) {
    return jsonResponse(400, {
      error: { code: "INVALID_REQUEST", message: "Malformed webhook event." },
    });
  }

  try {
    const eventsClient = await ensureTable(EVENTS_TABLE);
    try {
      await eventsClient.createEntity({
        partitionKey: EVENTS_PARTITION,
        rowKey: payload.event_id,
        eventType: payload.event_type,
        occurredAt: payload.occurred_at,
        processedAt: nowIso(),
      });
    } catch (err) {
      if (err instanceof RestError && err.statusCode === 409) {
        return jsonResponse(200, { received: true }); // duplicate delivery
      }
      throw err;
    }

    const patch = buildEventPatch(payload.event_type, payload.data);
    if (!patch) {
      return jsonResponse(200, { received: true }); // unhandled event type
    }

    const email = await resolveUserEmail(payload.data);
    if (!email) {
      context.warn(`paddle.orphan_event: ${payload.event_id} (${payload.event_type})`);
      return jsonResponse(200, { received: true });
    }

    const user = await getByEmail(email);
    if (
      user?.paddleEventOccurredAt &&
      Date.parse(user.paddleEventOccurredAt) >= Date.parse(payload.occurred_at)
    ) {
      return jsonResponse(200, { received: true }); // stale (out-of-order)
    }

    await applySubscriptionState(email, {
      ...patch,
      paddleEventOccurredAt: payload.occurred_at,
    });
    return jsonResponse(200, { received: true });
  } catch (err) {
    context.error("paddle-webhook storage failure:", err);
    return jsonResponse(500, {
      error: { code: "SERVICE_ERROR", message: "Webhook processing failed." },
    });
  }
}

app.http("paddle-webhook", {
  methods: ["POST"],
  authLevel: "anonymous",
  route: "paddle-webhook",
  handler: paddleWebhookHandler,
});