File size: 3,243 Bytes
689359a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { randomUUID } from "crypto";

import { buildBackendAuthHeaders } from "@/lib/backend-auth";

export const DEFAULT_FORWARDED_HEADERS = [
  "accept-ranges",
  "cache-control",
  "content-length",
  "content-range",
  "content-disposition",
  "content-type",
  "etag",
  "last-modified",
  "location",
  "x-trace-id",
] as const;

export function getBackendApiBaseUrl() {
  const apiUrl =
    process.env.BACKEND_INTERNAL_URL ||
    process.env.NEXT_PUBLIC_API_URL ||
    "http://localhost:8000";

  return apiUrl.replace(/\/$/, "");
}

export function buildBackendUrl(path: string) {
  return `${getBackendApiBaseUrl()}${path.startsWith("/") ? path : `/${path}`}`;
}

const TRACE_ID_PATTERN = /^[A-Za-z0-9._-]{8,128}$/;

/** Which app made the request. The backend evaluates feature flags per platform. */
export const CLIENT_HEADER = "x-supoclip-client";

/**
 * Headers every backend call carries from the incoming request:
 *
 * - `x-trace-id` (set per request in `lib/trace-fetch.ts`) so backend logs and
 *   PostHog errors share an id. Outside a request, or when the header is
 *   missing or malformed, a fresh id is used.
 * - `x-supoclip-client: ios` when the iOS app sent it, so feature flags are
 *   evaluated for iOS. Anything else is web, and isn't forwarded.
 */
export async function backendTraceHeaders(): Promise<Record<string, string>> {
  let trace: string | null = null;
  let client: string | null = null;
  try {
    const { headers } = await import("next/headers");
    const incoming = await headers();
    trace = incoming.get("x-trace-id");
    client = incoming.get(CLIENT_HEADER);
  } catch {
    // Not inside a request scope (scripts, tests).
  }
  return {
    "x-trace-id": trace && TRACE_ID_PATTERN.test(trace) ? trace : randomUUID(),
    ...(client?.trim().toLowerCase() === "ios" ? { [CLIENT_HEADER]: "ios" } : {}),
  };
}

export async function fetchBackend(
  path: string,
  init: RequestInit & {
    userId?: string;
    extraHeaders?: HeadersInit;
  } = {},
) {
  const { userId, extraHeaders, headers, ...rest } = init;

  return fetch(buildBackendUrl(path), {
    redirect: "manual",
    ...rest,
    headers: {
      ...(await backendTraceHeaders()),
      ...(userId ? buildBackendAuthHeaders(userId) : {}),
      ...(headers ?? {}),
      ...(extraHeaders ?? {}),
    },
  });
}

export function createProxyResponse(
  upstream: Response,
  forwardedHeaders: readonly string[] = DEFAULT_FORWARDED_HEADERS,
) {
  const responseHeaders = new Headers();
  for (const headerName of forwardedHeaders) {
    const value = upstream.headers.get(headerName);
    if (value) {
      responseHeaders.set(headerName, value);
    }
  }

  return new Response(upstream.body, {
    status: upstream.status,
    headers: responseHeaders,
  });
}

export async function createTextProxyResponse(
  upstream: Response,
  contentTypeFallback = "application/json",
) {
  const body = await upstream.text();
  return new Response(body, {
    status: upstream.status,
    headers: {
      "Content-Type": upstream.headers.get("content-type") || contentTypeFallback,
      ...(upstream.headers.get("x-trace-id")
        ? { "x-trace-id": upstream.headers.get("x-trace-id") as string }
        : {}),
    },
  });
}