Skip to content

Open-source status page, incident response and uptime monitoring

6.5 KB
Raw Blame
import { Events, setupAnalytics } from "@openstatus/analytics";
import { AVAILABLE_REGIONS } from "@openstatus/regions";
import { after } from "next/server";
import { z } from "zod";

import { mockCheckRegion } from "../../../../../lib/checker/mock";
import {
  type Method,
  checkRegion,
  getTimingPhases,
  storeBaseCheckerData,
  storeCheckerData,
} from "../../../../../lib/checker/utils";
import {
  PLAY_RATE_LIMIT_TIERS,
  getClientIP,
  rateLimitMessage,
  ratelimitTiers,
  retryAfterHeader,
  tieredRateLimitHeaders,
} from "../../../../../lib/ratelimit";
import { iteratorToStream, yieldMany } from "../../../../../lib/stream";
import { wait } from "../../../../../lib/utils";

export const runtime = "edge";

// Request schema validation
const playCheckerRequestSchema = z.object({
  url: z.url("Invalid URL format"),
  method: z
    .enum(["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"])
    .default("GET"),
  headers: z
    .array(
      z.object({
        key: z.string(),
        value: z.string(),
      }),
    )
    .optional(),
  body: z.string().optional(),
});

type PlayCheckerRequest = z.infer<typeof playCheckerRequestSchema>;

// Error response types
type ErrorCode =
  | "RATE_LIMIT_EXCEEDED"
  | "INVALID_REQUEST"
  | "NO_CLIENT_IP"
  | "INTERNAL_ERROR";

interface ErrorResponse {
  error: string;
  code: ErrorCode;
  details?: Record<string, unknown>;
  limit?: number;
  remaining?: number;
  reset?: number;
}

function createErrorResponse(
  code: ErrorCode,
  error: string,
  status: number,
  details?: Record<string, unknown>,
  headers?: Record<string, string>,
): Response {
  const response: ErrorResponse = {
    error,
    code,
    ...details,
  };

  return new Response(JSON.stringify(response), {
    status,
    headers: {
      "Content-Type": "application/json",
      ...headers,
    },
  });
}

const encoder = new TextEncoder();

async function* makeIterator({
  url,
  method,
  id,
  compact,
}: {
  url: string;
  method: Method;
  id: string;
  // used for openstatushq/skills:global-speed-checker to reduce size of the response
  compact: boolean;
}) {
  // Create an array to store all the promises
  const promises = AVAILABLE_REGIONS.map(async (region, index) => {
    try {
      console.log(`Checking ${region}...`);
      // Perform the fetch operation
      const check =
        process.env.NODE_ENV === "production"
          ? await checkRegion({ url, region, method })
          : await mockCheckRegion(region);

      if ("body" in check) {
        check.body = undefined; // Drop the body to avoid storing it in Redis Cache
      }

      if (check.state === "success") {
        await storeCheckerData({ check, id });
      }

      // compact mode: remove headers and body and use calculated timing
      const result =
        compact && check.state === "success"
          ? (() => {
              const { headers: _h, body: _b, timing, ...rest } = check;
              return { ...rest, timing: getTimingPhases(timing) };
            })()
          : check;

      return encoder.encode(
        `${JSON.stringify({
          ...result,
          index,
        })}\n`,
      );
    } catch (error) {
      console.log(error);
      // Stream the failure so the client doesn't stop at N-1 regions.
      return encoder.encode(
        `${JSON.stringify({
          state: "error",
          region,
          message: "Check failed in this region",
          index,
        })}\n`,
      );
    }
  });

  yield* yieldMany(promises);
  // return the id as the last value
  yield* generator(id);
}

async function* generator(id: string) {
  // wait for 200ms to avoid racing condition with the last check
  await wait(200);

  yield await Promise.resolve(encoder.encode(id));
}

export async function POST(request: Request) {
  // Parse and validate request body
  let requestData: PlayCheckerRequest;

  try {
    const json = await request.json();
    const parsed = playCheckerRequestSchema.safeParse(json);

    if (!parsed.success) {
      return createErrorResponse(
        "INVALID_REQUEST",
        "Invalid request format",
        400,
        {
          details: {
            issues: parsed.error.issues.map((issue) => ({
              field: issue.path.join("."),
              message: issue.message,
            })),
          },
        },
      );
    }

    requestData = parsed.data;
  } catch (_error) {
    return createErrorResponse(
      "INVALID_REQUEST",
      "Invalid JSON in request body",
      400,
    );
  }

  const { url, method } = requestData;

  const urlObject = new URL(url);

  if (
    urlObject.hostname.includes("openstatus.dev") &&
    urlObject.pathname.startsWith("/play/checker/api")
  ) {
    return createErrorResponse(
      "INVALID_REQUEST",
      "Self-requests are not allowed",
      400,
    );
  }

  try {
    const blacklistPatterns = (process.env.BLACKLIST_URL ?? "")
      .split(",")
      .map((p) => p.trim())
      .filter(Boolean);

    if (blacklistPatterns.some((pattern) => new RegExp(pattern).test(url))) {
      return createErrorResponse(
        "INVALID_REQUEST",
        "This URL is not allowed",
        403,
      );
    }
  } catch (error) {
    console.error("Error checking blacklist", error);
  }

  // Rate limiting check
  const clientIP = getClientIP(request.headers);

  if (!clientIP) {
    return createErrorResponse(
      "NO_CLIENT_IP",
      "Unable to determine client IP address",
      400,
    );
  }

  const rateLimitResult = await ratelimitTiers(
    `play-checker:${clientIP}`,
    PLAY_RATE_LIMIT_TIERS,
  );

  if (!rateLimitResult.success) {
    return createErrorResponse(
      "RATE_LIMIT_EXCEEDED",
      rateLimitMessage(rateLimitResult.tier),
      429,
      {
        limit: rateLimitResult.limit,
        remaining: rateLimitResult.remaining,
        reset: rateLimitResult.reset,
      },
      {
        ...tieredRateLimitHeaders(rateLimitResult),
        ...retryAfterHeader(rateLimitResult),
      },
    );
  }

  const compact = new URL(request.url).searchParams.get("compact") === "true";
  const uuid = crypto.randomUUID().replace(/-/g, "");
  after(async () => {
    const analytics = await setupAnalytics({ source: "web" });
    const additionalProps = { url, uuid, compact };
    await analytics.track({ ...Events.GlobalSpeedChecker, ...additionalProps });
  });
  await storeBaseCheckerData({ url, method, id: uuid });

  const iterator = makeIterator({
    url,
    method,
    id: uuid,
    compact,
  });
  const stream = iteratorToStream(iterator);
  return new Response(stream, {
    headers: tieredRateLimitHeaders(rateLimitResult),
  });
}